import { useEffect, useState, useCallback } from "react";

export interface ServerStatus {
  state: boolean; // true = online, false = offline
  phase: string; // "starting", "ready", "stopped", "stopping", etc
  message: string; // Message du CPU
  isLoading: boolean;
  refetch: () => void;
}

export function useGPUServerStatus(checkInterval: number = 1000): ServerStatus {
  const [state, setState] = useState(false);
  const [phase, setPhase] = useState("stopped");
  const [message, setMessage] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  const checkServerStatus = useCallback(async () => {
    try {
      // Requête via le backend proxy (pas de CORS)
      const response = await fetch("/api/healthGPU1", {
        method: "GET",
        signal: AbortSignal.timeout(5000),
      });

      if (response.ok) {
        const data = await response.json();
        console.log("[useGPUServerStatus] Raw data from healthGPU1:", data);

        // Le backend retourne le status du CPU
        // data.status = "online" | "offline" | "starting" | "stopping"
        let newState = false;
        let newPhase = "stopped";
        const newMessage = data.payload?.details || data.message || "Unknown";

        // Mapper le status en state/phase
        if (data.status === "online") {
          newState = true;
          newPhase = "ready";
        } else if (data.status === "starting") {
          newState = false;
          newPhase = "starting";
        } else if (data.status === "stopping") {
          newState = false;
          newPhase = "stopping";
        } else if (data.status === "offline") {
          newState = false;
          newPhase = "stopped";
        }

        console.log("[useGPUServerStatus] Parsed:", {
          status: data.status,
          state: newState,
          phase: newPhase,
          message: newMessage,
        });

        setState(newState);
        setPhase(newPhase);
        setMessage(newMessage);
      } else {
        console.log("[useGPUServerStatus] Error response:", response.status);
        setState(false);
        setPhase("stopped");
        setMessage("Error checking server");
      }
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error";
      console.log("[useGPUServerStatus] Fetch error:", errorMessage);
      setState(false);
      setPhase("stopped");
      setMessage(errorMessage);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    checkServerStatus();
    const interval = setInterval(checkServerStatus, checkInterval);
    return () => clearInterval(interval);
  }, [checkServerStatus, checkInterval]);

  return {
    state,
    phase,
    message,
    isLoading,
    refetch: checkServerStatus,
  };
}
