"use client";

import { useState, useEffect, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import {
  fetchClusterHealth,
  type ClusterHealth as ClusterHealthType,
  ApiError,
} from "@/app/lib/api";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { ScrollArea } from "./ui/scroll-area";
import { toast } from "sonner";
import {
  Activity,
  RefreshCw,
  Loader2,
  Clock,
  Download,
  Server,
  Cpu,
  AlertCircle,
  Gauge,
} from "lucide-react";
import { cn } from "@/app/lib/utils";

function formatBytes(bps: number): string {
  if (bps >= 1_000_000) return `${(bps / 1_000_000)?.toFixed(1)} MB/s`;
  if (bps >= 1_000) return `${(bps / 1_000)?.toFixed(1)} KB/s`;
  return `${Math.round(bps)} B/s`;
}

function latencyColor(ms: number): string {
  if (ms < 80) return "text-success";
  if (ms < 150) return "text-warning";
  return "text-destructive";
}

function StatusDot({ online }: { online: boolean }) {
  return (
    <div
      className={cn(
        "h-2 w-2 rounded-full",
        online
          ? "bg-success shadow-[0_0_6px_rgb(34_197_94/0.5)]"
          : "bg-destructive shadow-[0_0_6px_rgb(239_68_68/0.5)]",
      )}
    />
  );
}

export default function ClusterHealth() {
  const { baseUrl, apiKey } = useSettings();
  const [health, setHealth] = useState<ClusterHealthType | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);

  const loadHealth = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await fetchClusterHealth({ baseUrl, apiKey });
      setHealth(data);
      setLastRefresh(new Date());
    } catch (err) {
      const msg =
        err instanceof ApiError
          ? err.message
          : "Failed to fetch cluster health";
      setError(msg);
      toast.error("Health check failed", { description: msg });
    } finally {
      setLoading(false);
    }
  }, [baseUrl, apiKey]);

  useEffect(() => {
    loadHealth();
  }, [loadHealth]);

  const onlineMirrors =
    health?.mirrors?.filter((m) => m.status === "online").length ?? 0;
  const totalMirrors = health?.mirrors?.length ?? 0;

  return (
    <div className="flex flex-1 flex-col min-h-0">
      {/* Header */}
      <div className="flex items-center gap-3 border-b border-border px-6 py-3">
        <Activity className="h-4 w-4 text-primary" />
        <h2 className="text-sm font-semibold text-foreground">
          Cluster Health
        </h2>
        <Badge variant="secondary" className="text-caption font-mono">
          {(() => {
            try {
              return new URL(baseUrl).hostname;
            } catch {
              return baseUrl;
            }
          })()}
        </Badge>
        <div className="flex-1" />
        {lastRefresh && (
          <span className="text-caption text-muted-foreground">
            Last check: {lastRefresh.toLocaleTimeString()}
          </span>
        )}
        <Button
          variant="outline"
          size="sm"
          onClick={loadHealth}
          disabled={loading}
        >
          {loading ? (
            <Loader2 className="h-3 w-3 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3" />
          )}
          Refresh
        </Button>
      </div>

      {/* Error state */}
      {error && !loading && (
        <div className="flex items-center gap-2 border-b border-destructive-border bg-destructive-subtle px-6 py-3 text-xs text-destructive">
          <AlertCircle className="h-3.5 w-3.5" />
          {error}
          <Button
            variant="outline"
            size="sm"
            onClick={loadHealth}
            className="ml-auto h-6 text-caption"
          >
            Retry
          </Button>
        </div>
      )}

      {/* Loading */}
      {loading && !health && (
        <div className="flex flex-1 items-center justify-center">
          <div className="flex flex-col items-center gap-3">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="text-xs text-muted-foreground">
              Checking cluster health…
            </p>
          </div>
        </div>
      )}

      {health && (
        <ScrollArea className="flex-1">
          <div className="mx-auto max-w-4xl space-y-6 p-6">
            {/* Overview cards */}
            <div className="grid grid-cols-4 gap-4">
              <div className="rounded-lg border border-border bg-card p-4">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                  <Cpu className="h-4 w-4" />
                  <span className="text-caption uppercase tracking-wider">
                    API
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <StatusDot online={health.athena_api === "online"} />
                  <span className="text-sm font-semibold capitalize">
                    {health.athena_api}
                  </span>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-card p-4">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                  <Server className="h-4 w-4" />
                  <span className="text-caption uppercase tracking-wider">
                    Deadpool
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <StatusDot online={health.athena_deadpool === "online"} />
                  <span className="text-sm font-semibold capitalize">
                    {health.athena_deadpool}
                  </span>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-card p-4">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                  <Server className="h-4 w-4" />
                  <span className="text-caption uppercase tracking-wider">
                    ScyllaDB
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <StatusDot online={health.athena_scylladb === "online"} />
                  <span className="text-sm font-semibold capitalize">
                    {health.athena_scylladb}
                  </span>
                </div>
              </div>
              <div className="rounded-lg border border-border bg-card p-4">
                <div className="flex items-center gap-2 text-muted-foreground mb-2">
                  <Gauge className="h-4 w-4" />
                  <span className="text-caption uppercase tracking-wider">
                    Mirrors
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm font-semibold">
                    {onlineMirrors}/{totalMirrors}
                  </span>
                  <Badge
                    variant={
                      onlineMirrors === totalMirrors ? "success" : "warning"
                    }
                    className="text-caption"
                  >
                    {onlineMirrors === totalMirrors
                      ? "all healthy"
                      : "degraded"}
                  </Badge>
                </div>
              </div>
            </div>

            {/* Version */}
            <div className="flex items-center gap-4 rounded-lg border border-border bg-card px-5 py-3">
              <span className="text-xs text-muted-foreground">
                Server version
              </span>
              <Badge variant="default" className="font-mono">
                v{health.version}
              </Badge>
              <span className="text-caption text-muted-foreground">
                Cargo.toml: v{health.cargo_toml_version}
              </span>
            </div>

            {/* Mirrors table */}
            <section>
              <h3 className="mb-3 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                Mirror instances
              </h3>
              <div className="rounded-lg border border-border overflow-hidden">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border bg-muted-panel">
                      <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                        URL
                      </th>
                      <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                        Status
                      </th>
                      <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                        Version
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Latency
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Throughput
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/50">
                    {(health.mirrors ?? []).map((mirror) => (
                      <tr
                        key={mirror.url}
                        className="hover:bg-accent-muted transition-colors"
                      >
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <StatusDot online={mirror.status === "online"} />
                            <span className="text-xs font-mono text-foreground">
                              {mirror.url}
                            </span>
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <Badge
                            variant={
                              mirror.status === "online"
                                ? "success"
                                : "destructive"
                            }
                            className="text-caption"
                          >
                            {mirror.status}
                          </Badge>
                        </td>
                        <td className="px-4 py-3">
                          <span className="text-xs font-mono text-muted-foreground">
                            v{mirror.cargo_toml_version}
                          </span>
                          {mirror.cargo_toml_version !==
                            health.cargo_toml_version && (
                            <Badge variant="warning" className="ml-2 text-tiny">
                              outdated
                            </Badge>
                          )}
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span
                            className={cn(
                              "flex items-center justify-end gap-1 text-xs font-mono",
                              latencyColor(mirror?.latency_ms ?? 0),
                            )}
                          >
                            <Clock className="h-3 w-3" />
                            {mirror?.latency_ms?.toFixed(1)}ms
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="flex items-center justify-end gap-1 text-xs font-mono text-muted-foreground">
                            <Download className="h-3 w-3" />
                            {formatBytes(mirror?.download_bytes_per_sec ?? 0)}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>

            {/* Raw JSON */}
            <section>
              <h3 className="mb-3 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                Raw response
              </h3>
              <pre className="max-h-[300px] overflow-auto rounded-lg border border-border bg-muted p-3 font-mono text-caption text-muted-foreground leading-relaxed">
                {JSON.stringify(health, null, 2)}
              </pre>
            </section>
          </div>
        </ScrollArea>
      )}
    </div>
  );
}
