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

/**
 * Generic polling hook — calls fetcher every `interval` ms.
 * Returns { data, error, loading, refetch }.
 */
export function usePolling<T>(
  fetcher: () => Promise<T>,
  interval: number = 5000,
) {
  const [data, setData] = useState<T | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  const refetch = useCallback(async () => {
    try {
      const result = await fetcher()
      setData(result)
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e))
    } finally {
      setLoading(false)
    }
  }, [fetcher])

  useEffect(() => {
    refetch()
    const id = setInterval(refetch, interval)
    return () => clearInterval(id)
  }, [refetch, interval])

  return { data, error, loading, refetch }
}
