import { useCallback, useEffect, useState } from 'react'
import { backendClient } from '../api/backend'
import type {
  DailyEnergyFlows,
  DailyEnergyFlowsResponse,
  IntervalEnergyFlows,
} from '../types/energy-flows'

export function useEnergyFlowsDaily(siteId: number | null, month: string) {
  const [days, setDays] = useState<DailyEnergyFlows[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const load = useCallback(async () => {
    if (siteId == null || !month) return
    setLoading(true)
    setError(null)
    try {
      const { data } = await backendClient.get<DailyEnergyFlowsResponse>(
        `/sites/${siteId}/energy-flows/daily`,
        { params: { month }, timeout: 30_000 },
      )
      setDays(data.days ?? [])
    } catch {
      setDays([])
      setError('Nepodařilo se načíst toky energie')
    } finally {
      setLoading(false)
    }
  }, [siteId, month])

  useEffect(() => {
    void load()
  }, [load])

  return { days, loading, error, reload: load }
}

export function useEnergyFlowsIntervals(siteId: number | null, day: string | null) {
  const [intervals, setIntervals] = useState<IntervalEnergyFlows[]>([])
  const [loading, setLoading] = useState(false)

  const load = useCallback(async () => {
    if (siteId == null || !day) {
      setIntervals([])
      return
    }
    setLoading(true)
    try {
      const { data } = await backendClient.get<IntervalEnergyFlows[]>(
        `/sites/${siteId}/energy-flows/daily/${day}/intervals`,
        { timeout: 30_000 },
      )
      setIntervals(Array.isArray(data) ? data : [])
    } catch {
      setIntervals([])
    } finally {
      setLoading(false)
    }
  }, [siteId, day])

  useEffect(() => {
    void load()
  }, [load])

  return { intervals, loading }
}
