"use client";

import { useState, useCallback, useEffect, useRef, useMemo } from "react";
import {
  StemeDBClient,
  type CircuitBreakerResponse,
  type CircuitBreakerStatus,
  ApiError,
} from "@/lib/api";
import type { PanelState } from "@/lib/types";
import { CIRCUIT_POLL_INTERVAL_MS } from "@/lib/constants";
import { ErrorState } from "@/components/shared/error-state";
import { CircuitSummary } from "./circuit-summary";
import { CircuitList } from "./circuit-list";
import { CircuitLoadingSkeleton } from "./circuit-loading-skeleton";
import { CircuitEmptyState } from "./circuit-empty-state";

// Transform backend response to component format
function toCircuitBreakerStatus(
  circuit: CircuitBreakerResponse["circuits"][0]
): CircuitBreakerStatus {
  return {
    name: circuit.agent_id,
    state: circuit.state,
    failure_count: circuit.failure_count,
    success_count: 0, // Not provided by backend
    last_failure: circuit.last_failure_time
      ? new Date(circuit.last_failure_time * 1000).toISOString()
      : undefined,
    last_state_change: circuit.last_trip_time ?? 0,
    timeout_seconds: circuit.retry_after_secs ?? 0,
  };
}

export function CircuitPanel() {
  const [state, setState] = useState<PanelState<CircuitBreakerResponse>>({ status: "idle" });
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);

  const fetchData = useCallback(async (isPolling = false) => {
    // Only show loading skeleton on initial load, not during polling
    if (!isPolling) {
      setState({ status: "loading" });
    }

    try {
      const client = new StemeDBClient();
      const data = await client.circuitBreakers();
      setState({ status: "success", data });
      setLastUpdated(new Date());
    } catch (err) {
      // 404 means no circuit breakers - treat as empty success
      if (err instanceof ApiError && err.status === 404) {
        setState({ status: "success", data: { circuits: [], count: 0 } });
        setLastUpdated(new Date());
        return;
      }
      const message =
        err instanceof ApiError
          ? err.userMessage
          : err instanceof Error
            ? err.message
            : "Unknown error";
      // Only show error on initial load, not during polling failures
      if (!isPolling) {
        setState({ status: "error", error: message });
      }
    }
  }, []);

  // Initial load
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // Set up polling
  useEffect(() => {
    pollIntervalRef.current = setInterval(() => {
      fetchData(true);
    }, CIRCUIT_POLL_INTERVAL_MS);

    return () => {
      if (pollIntervalRef.current) {
        clearInterval(pollIntervalRef.current);
      }
    };
  }, [fetchData]);

  const handleReset = useCallback(
    async (name: string) => {
      try {
        const client = new StemeDBClient();
        await client.resetCircuitBreaker(name);
        // Refresh after reset
        await fetchData();
      } catch (err) {
        const message = err instanceof Error ? err.message : "Failed to reset";
        // Show error briefly
        setState({ status: "error", error: message });
      }
    },
    [fetchData]
  );

  const handleRetry = useCallback(() => {
    fetchData();
  }, [fetchData]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="rounded-lg border border-border bg-card p-6">
        <div className="flex items-center justify-between mb-2">
          <h2 className="text-lg font-medium text-card-foreground">
            System Health & Resilience
          </h2>
          {lastUpdated && (
            <span className="text-xs text-muted-foreground">
              Updated {lastUpdated.toLocaleTimeString()}
            </span>
          )}
        </div>
        <p className="text-sm text-muted-foreground">
          Monitor circuit breaker states across the system. Reset breakers
          manually when issues are resolved. Auto-refreshes every 10 seconds.
        </p>
      </div>

      {/* Content */}
      <div className="rounded-lg border border-border bg-card p-6">
        {state.status === "idle" && <CircuitLoadingSkeleton />}
        {state.status === "loading" && <CircuitLoadingSkeleton />}

        {state.status === "error" && (
          <ErrorState
            title="Failed to Load Circuit Breakers"
            error={state.error}
            onRetry={handleRetry}
          />
        )}

        {state.status === "success" && (
          <div className="space-y-6">
            {state.data.circuits.length === 0 ? (
              <CircuitEmptyState />
            ) : (
              <>
                <CircuitSummary
                  breakers={state.data.circuits.map(toCircuitBreakerStatus)}
                />
                <CircuitList
                  breakers={state.data.circuits.map(toCircuitBreakerStatus)}
                  onReset={handleReset}
                />
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
