"use client";

import { useEffect, useState } from "react";
import {
  Database,
  Activity,
  RefreshCw,
  CheckCircle2,
  XCircle,
  AlertCircle,
} from "lucide-react";
import type { SystemOverview } from "@/lib/types/admin-panel";

export function SystemHealthClient() {
  const [data, setData] = useState<SystemOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date());

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/staff/admin/system-overview");
      if (!res.ok) {
        throw new Error("Failed to fetch system overview");
      }
      const json = await res.json();
      setData(json);
      setLastRefresh(new Date());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    // Auto-refresh every 30 seconds
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, []);

  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    if (days > 0) return `${days}d ${hours}h ${mins}m`;
    if (hours > 0) return `${hours}h ${mins}m`;
    return `${mins}m`;
  };

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-6">
        <div className="flex items-center gap-2 text-red-800">
          <XCircle className="w-5 h-5" />
          <span className="font-medium">Error loading system health</span>
        </div>
        <p className="text-red-600 mt-2">{error}</p>
        <button
          onClick={fetchData}
          className="mt-4 px-4 py-2 bg-red-100 text-red-800 rounded-lg hover:bg-red-200 transition"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header with refresh */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          Last updated: {lastRefresh.toLocaleTimeString()}
        </p>
        <button
          onClick={fetchData}
          disabled={loading}
          className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-600 hover:text-brand-primary hover:bg-gray-100 rounded-lg transition disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      {/* System Info */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-xs text-gray-500 uppercase tracking-wide">
            Version
          </p>
          <p className="text-2xl font-bold text-gray-900 mt-1 font-mono">
            {data?.version || "..."}
          </p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-xs text-gray-500 uppercase tracking-wide">
            Commit
          </p>
          <p className="text-2xl font-bold text-gray-900 mt-1 font-mono">
            {data?.commit?.substring(0, 8) || "N/A"}
          </p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-xs text-gray-500 uppercase tracking-wide">
            Uptime
          </p>
          <p className="text-2xl font-bold text-gray-900 mt-1">
            {data?.uptime ? formatUptime(data.uptime) : "..."}
          </p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-xs text-gray-500 uppercase tracking-wide">
            Rate Limiter
          </p>
          <p
            className={`text-2xl font-bold mt-1 ${data?.rateLimiter.healthy ? "text-green-600" : "text-yellow-600"}`}
          >
            {data?.rateLimiter.mode || "..."}
          </p>
        </div>
      </div>

      {/* Service Health Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <ServiceCard
          name="Database (Prisma)"
          icon={Database}
          status={data?.database}
          loading={loading}
        />
        <ServiceCard
          name="Redis"
          icon={Activity}
          status={data?.redis}
          loading={loading}
        />
      </div>
    </div>
  );
}

function ServiceCard({
  name,
  icon: Icon,
  status,
  loading,
}: {
  name: string;
  icon: React.ComponentType<{ className?: string }>;
  status?: { healthy: boolean; latency?: number; error?: string };
  loading: boolean;
}) {
  return (
    <div className="bg-white border border-gray-200 rounded-xl p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div
            className={`w-10 h-10 rounded-lg flex items-center justify-center ${
              status?.healthy
                ? "bg-green-100"
                : status
                  ? "bg-red-100"
                  : "bg-gray-100"
            }`}
          >
            <Icon
              className={`w-5 h-5 ${
                status?.healthy
                  ? "text-green-600"
                  : status
                    ? "text-red-600"
                    : "text-gray-400"
              }`}
            />
          </div>
          <span className="font-semibold text-gray-900">{name}</span>
        </div>
        {loading ? (
          <div className="w-3 h-3 rounded-full bg-gray-300 animate-pulse" />
        ) : status?.healthy ? (
          <CheckCircle2 className="w-5 h-5 text-green-500" />
        ) : status ? (
          <XCircle className="w-5 h-5 text-red-500" />
        ) : (
          <AlertCircle className="w-5 h-5 text-gray-400" />
        )}
      </div>

      <div className="space-y-2">
        <div className="flex items-center justify-between text-sm">
          <span className="text-gray-500">Status</span>
          <span
            className={`font-medium ${
              status?.healthy
                ? "text-green-600"
                : status
                  ? "text-red-600"
                  : "text-gray-400"
            }`}
          >
            {loading
              ? "..."
              : status?.healthy
                ? "Healthy"
                : status
                  ? "Unhealthy"
                  : "Unknown"}
          </span>
        </div>
        {status?.latency !== undefined && (
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-500">Latency</span>
            <span className="font-mono text-gray-900">{status.latency}ms</span>
          </div>
        )}
        {status?.error && (
          <div className="mt-3 p-2 bg-red-50 rounded text-xs text-red-600">
            {status.error}
          </div>
        )}
      </div>
    </div>
  );
}
