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

import { getSiteNotifications } from '../api/backend'
import type { Notification } from '../types/dashboard'

const POLL_MS = 60_000

export function useNotifications(siteId: number | null) {
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(async (silent?: boolean) => {
    if (siteId == null) {
      setNotifications([])
      setError(null)
      setLoading(false)
      return
    }
    if (!silent) setLoading(true)
    try {
      const res = await getSiteNotifications(siteId)
      setNotifications(res.notifications)
      setError(null)
    } catch {
      setNotifications([])
      setError('Notifikace se nepodařilo načíst')
    } finally {
      if (!silent) setLoading(false)
    }
  }, [siteId])

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

  return {
    notifications,
    loading,
    error,
    reload: () => void load(false),
  }
}
