import { useCallback, useEffect, useState } from 'react'
import { getJson } from '../api/postgrest'
import { instantPragueDay, pragueCalendarDay } from '../lib/pragueDate'
import type { AuditDailyRow } from '../types/ems'

const POLL_MS = 30_000

export function useAuditDailyToday(siteId: number | null) {
  const [row, setRow] = useState<AuditDailyRow | null>(null)
  const [ready, setReady] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(async () => {
    if (siteId == null) {
      setRow(null)
      setError(null)
      setReady(true)
      return
    }
    try {
      const today = pragueCalendarDay()
      let primary = await getJson<AuditDailyRow[]>('/vw_audit_daily', {
        site_id: `eq.${siteId}`,
        day_local: `eq.${today}`,
      })
      let chosen: AuditDailyRow | null = null
      if (Array.isArray(primary) && primary.length > 0) {
        chosen = primary.find((r) => instantPragueDay(r.day_local) === today) ?? null
      }
      if (chosen == null || instantPragueDay(chosen.day_local) !== today) {
        const recent = await getJson<AuditDailyRow[]>('/vw_audit_daily', {
          site_id: `eq.${siteId}`,
          order: 'day_local.desc',
          limit: '45',
        })
        chosen = Array.isArray(recent)
          ? recent.find((r) => instantPragueDay(r.day_local) === today) ?? null
          : null
      }
      setRow(chosen)
      setError(null)
    } catch {
      setRow(null)
      setError('Denní souhrn auditu se nepodařil načíst')
    } finally {
      setReady(true)
    }
  }, [siteId])

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

  return {
    daily: row,
    ready,
    error,
    hasDaily: row != null && (row.interval_count ?? 0) > 0,
    reload: load,
  }
}
