import { useCallback, useEffect, useState } from 'react'
import axios from 'axios'

import { getCurrentPlan } from '../api/backend'
import type { CurrentPlanResponse } from '../types/plan'

const POLL_MS = 30_000

const EMPTY: CurrentPlanResponse = { run: null, intervals: [], summary: null }

export function useCurrentPlan(siteId: number | null) {
  const [data, setData] = useState<CurrentPlanResponse>(EMPTY)
  const [ready, setReady] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(async () => {
    if (siteId == null) {
      setData(EMPTY)
      setError(null)
      setReady(true)
      return
    }
    try {
      const res = await getCurrentPlan(siteId)
      setData(res)
      setError(null)
    } catch (e) {
      if (axios.isAxiosError(e) && e.response?.status === 404) {
        setData(EMPTY)
        setError(null)
      } else {
        setData(EMPTY)
        setError(e instanceof Error ? e.message : 'Nepodařilo se načíst plán')
      }
    } finally {
      setReady(true)
    }
  }, [siteId])

  useEffect(() => {
    void load()
    const id = window.setInterval(() => void load(), POLL_MS)
    return () => window.clearInterval(id)
  }, [load])

  return { plan: data, ready, error, reload: load }
}
