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

import { getBackendHealthDetailed } from '../api/backend'

/** Minuty do dalšího naplánovaného `rolling_replan` jobu (globální scheduler). */
export function useRollingReplanMinutes() {
  const [nextReplanIn, setNextReplanIn] = useState<number | null>(null)

  const refresh = useCallback(async () => {
    try {
      const h = await getBackendHealthDetailed()
      const job = h.active_jobs.find((j) => j.id === 'rolling_replan')
      if (job?.next_run_time == null) {
        setNextReplanIn(null)
        return
      }
      const diffMin = (new Date(job.next_run_time).getTime() - Date.now()) / 60_000
      setNextReplanIn(Math.max(0, Math.round(diffMin)))
    } catch {
      setNextReplanIn(null)
    }
  }, [])

  useEffect(() => {
    void refresh()
    const id = window.setInterval(() => void refresh(), 60_000)
    return () => window.clearInterval(id)
  }, [refresh])

  return { nextReplanIn, refreshRollingEta: refresh }
}
