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

import { getSiteStatusFull } from '../api/backend'
import type { FullStatusResponse } from '../types/fullStatus'

const POLL_MS = 120_000

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

  const load = useCallback(async () => {
    if (siteId == null) {
      setData(null)
      setError(null)
      setReady(true)
      return
    }
    try {
      const res = await getSiteStatusFull(siteId)
      setData(res)
      setError(null)
    } catch {
      setData(null)
      setError('Monitoring stav se nepodařilo načíst')
    } finally {
      setReady(true)
    }
  }, [siteId])

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

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