/**
 * Monitoring - Clusters Page
 * 监控集群状态和健康信息
 */
import React, { useState, useEffect } from "react";
import { Activity, Database, Server, RefreshCw } from "lucide-react";
import { PageHeader, StatsCard, Button, LoadingState, ErrorState, EmptyState } from "@/shared";
import { useToast } from "@/shared";
import { ClusterErrors, SuccessMessages, formatApiError } from "@/shared/utils";
import { listClusterMonitoring } from "@/api";
import type { ClusterMetrics } from "@/core/types";
import { ClusterMonitorCard } from "../components/ClusterMonitorCard";

const MonitoringClustersPage: React.FC = () => {
  const { info: toastInfo, success: toastSuccess, error: toastError } = useToast();

  const [clusters, setClusters] = useState<ClusterMetrics[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  // Load cluster monitoring data
  const loadClusters = async (isMounted = { current: true }, isRefresh = false) => {
    let succeeded = false;
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);

    try {
      const data = await listClusterMonitoring();
      if (isMounted.current) {
        setClusters(data);
        succeeded = true;
      }
    } catch (err) {
      const errorMsg = formatApiError(err) || ClusterErrors.LOAD_FAILED;
      if (isMounted.current) {
        setError(errorMsg);
        toastError(errorMsg);
        console.error(err);
      }
    } finally {
      if (isMounted.current) {
        setLoading(false);
        setRefreshing(false);
      }
    }
    return succeeded;
  };

  useEffect(() => {
    const isMounted = { current: true };
    loadClusters(isMounted);

    // Auto-refresh every 30 seconds
    const interval = setInterval(() => {
      loadClusters(isMounted, true);
    }, 30000);

    return () => {
      isMounted.current = false;
      clearInterval(interval);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refresh clusters
  const handleRefresh = async () => {
    toastInfo("Refreshing cluster metrics...", {
      title: "Monitoring Refresh",
      durationMs: 1800,
      mergeKey: "monitoring-refresh",
    });
    const refreshed = await loadClusters({ current: true }, true);
    if (refreshed) {
      toastSuccess(SuccessMessages.DATA_REFRESHED);
    }
  };

  if (loading) {
    return <LoadingState message="Loading cluster monitoring data..." />;
  }

  if (error) {
    return (
      <ErrorState
        title="Failed to Load Clusters"
        message={error}
        onRetry={() => loadClusters({ current: true })}
      />
    );
  }

  if (clusters.length === 0) {
    return (
      <EmptyState
        icon={Server}
        title="No Clusters Available"
        description="No clusters configured for monitoring. Please add clusters in the configuration section."
      />
    );
  }

  const healthyCount = clusters.filter(c => c.status === "healthy").length;
  const warningCount = clusters.filter(c => c.status === "warning" || c.status === "unknown").length;
  const errorCount = clusters.filter(c => c.status === "error" || c.status === "unhealthy").length;
  const allocatedGpu = clusters.reduce(
    (sum, cluster) => sum + firstNumber(cluster.gpuAllocated, cluster.allocatedGpu, cluster.gpuAllocation, cluster.usedGpu),
    0
  );
  const totalGpu = clusters.reduce((sum, cluster) => sum + (cluster.totalGpu ?? 0), 0);
  const gpuMemoryText = summarizeGpuMemory(clusters);

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <PageHeader
        title="Cluster Monitoring"
        description="Monitor cluster health and status"
        icon={Activity}
      >
        <Button
          variant="secondary"
          icon={RefreshCw}
          onClick={handleRefresh}
          loading={refreshing}
        >
          {refreshing ? "Refreshing..." : "Refresh"}
        </Button>
      </PageHeader>

      {/* Summary Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-6 gap-4">
        <StatsCard
          title="Total Clusters"
          value={clusters.length}
          icon={Server}
          variant="blue"
        />
        <StatsCard
          title="Healthy"
          value={healthyCount}
          icon={Activity}
          variant="green"
        />
        <StatsCard
          title="Warning"
          value={warningCount}
          icon={Activity}
          variant="orange"
        />
        <StatsCard
          title="Error"
          value={errorCount}
          icon={Activity}
          variant="red"
        />
        <StatsCard
          title="GPU Allocation"
          value={`${allocatedGpu}/${totalGpu || "N/A"}`}
          icon={Activity}
          variant="purple"
        />
        <StatsCard
          title="GPU Mem"
          value={gpuMemoryText}
          icon={Database}
          variant="orange"
        />
      </div>

      {/* Auto-refresh Info */}
      <div className="text-sm text-slate-500">
        Auto-refresh every 30 seconds {refreshing && "• Refreshing..."}
      </div>

      {/* Cluster List */}
      <div className="grid gap-4">
        {clusters.map((cluster, index) => (
          <ClusterMonitorCard
            key={cluster.clusterId || cluster.id || `${cluster.clusterName || 'cluster'}-${index}`}
            cluster={cluster}
          />
        ))}
      </div>
    </div>
  );
};

export default MonitoringClustersPage;

const firstNumber = (...values: Array<number | undefined | null>): number => {
  for (const value of values) {
    if (typeof value === "number" && Number.isFinite(value)) {
      return value;
    }
  }
  return 0;
};

const summarizeGpuMemory = (clusters: ClusterMetrics[]): string => {
  const usedValues = clusters
    .map((cluster) => firstText(cluster.allocatedGpuMemoryMb, cluster.allocatedGpuMemoryMB, cluster.gpuMemoryRequestsMb, cluster.usedGpuMemory, cluster.gpuMemoryUsed, cluster.usedGpuMem))
    .filter(Boolean);
  const totalValues = clusters
    .map((cluster) => firstText(cluster.totalGpuMemory, cluster.totalGpuMem))
    .filter(Boolean);
  if (usedValues.length === 0 && totalValues.length === 0) {
    return "N/A";
  }
  if (usedValues.length === 1 && totalValues.length <= 1) {
    return totalValues[0] ? `${usedValues[0] || "0"} / ${totalValues[0]}` : usedValues[0];
  }
  return `${usedValues.length || 0} clusters`;
};

const firstText = (...values: Array<string | number | undefined | null>): string => {
  for (const value of values) {
    if (typeof value === "number" && Number.isFinite(value)) {
      return String(value);
    }
    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }
  return "";
};
