"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import type {
  StatusSnapshot,
  StatusSummaryInfo,
  StatusAlertInfo,
  StatusHostInfo,
  StatusServiceInfo,
  StatusNetworkInfo,
  StatusSiteInfo,
} from "@/lib/types";

export type SelectedItem =
  | { type: "host"; data: StatusHostInfo }
  | { type: "service"; data: StatusServiceInfo }
  | { type: "network"; data: StatusNetworkInfo }
  | { type: "site"; data: StatusSiteInfo }
  | null;

export interface UseStatusReturn {
  snapshot: StatusSnapshot | null;
  summary: StatusSummaryInfo | null;
  alerts: StatusAlertInfo[];
  loading: boolean;
  error: string | null;
  selectedItem: SelectedItem;
  selectItem: (item: SelectedItem) => void;
  refresh: () => void;
}

const POLL_INTERVAL = 15_000;

export function useStatus(): UseStatusReturn {
  const [snapshot, setSnapshot] = useState<StatusSnapshot | null>(null);
  const [summary, setSummary] = useState<StatusSummaryInfo | null>(null);
  const [alerts, setAlerts] = useState<StatusAlertInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedItem, setSelectedItem] = useState<SelectedItem>(null);
  const [refreshKey, setRefreshKey] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setError(null);
      const [statusRes, summaryRes, alertsRes] = await Promise.all([
        fetch("/api/status"),
        fetch("/api/status/summary"),
        fetch("/api/status/alerts"),
      ]);

      if (statusRes.ok) setSnapshot(await statusRes.json());
      if (summaryRes.ok) setSummary(await summaryRes.json());
      if (alertsRes.ok) setAlerts(await alertsRes.json());
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, [refreshKey]);

  useEffect(() => {
    fetchData();
    intervalRef.current = setInterval(fetchData, POLL_INTERVAL);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [fetchData]);

  const selectItem = useCallback((item: SelectedItem) => {
    setSelectedItem(item);
  }, []);

  const refresh = useCallback(() => {
    setRefreshKey((k) => k + 1);
  }, []);

  return {
    snapshot,
    summary,
    alerts,
    loading,
    error,
    selectedItem,
    selectItem,
    refresh,
  };
}
