"use client";

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

interface Check { name: string; status: "ok" | "warn" | "down"; detail: string }
interface Data { overall: "ok" | "warn" | "down"; checks: Check[]; checkedAt: string; error?: string }

const STATUS = {
  ok: { dot: "bg-emerald-400", text: "text-emerald-400", label: "Healthy" },
  warn: { dot: "bg-amber-400", text: "text-amber-400", label: "Degraded" },
  down: { dot: "bg-rose-500", text: "text-rose-400", label: "Down" },
};

export default function AdminHealth() {
  const [data, setData] = useState<Data | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(() => {
    setLoading(true);
    fetch("/api/admin/health", { credentials: "include" })
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(() => { setData(null); setLoading(false); });
  }, []);

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

  const overall = data?.overall || "warn";

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-start flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold">System Health</h1>
          <p className="text-gray-400">{data?.checkedAt ? `Checked ${new Date(data.checkedAt).toLocaleTimeString()}` : "Live status of core services"}</p>
        </div>
        <button onClick={load} className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 rounded-lg text-sm">↻ Refresh</button>
      </div>

      <div className="bg-gray-800 p-6 rounded-xl flex items-center gap-4">
        <span className={`w-4 h-4 rounded-full ${STATUS[overall].dot} ${overall !== "ok" ? "animate-pulse" : ""}`} />
        <div>
          <div className={`text-xl font-bold ${STATUS[overall].text}`}>{STATUS[overall].label}</div>
          <div className="text-sm text-gray-400">Overall system status</div>
        </div>
      </div>

      {loading ? (
        <div className="text-gray-400">Running checks…</div>
      ) : !data ? (
        <div className="bg-rose-500/10 text-rose-400 p-4 rounded-xl">Failed to load health checks.</div>
      ) : (
        <div className="bg-gray-800 rounded-xl divide-y divide-gray-700">
          {data.checks.map(c => (
            <div key={c.name} className="flex items-center gap-4 p-4">
              <span className={`w-3 h-3 rounded-full flex-shrink-0 ${STATUS[c.status].dot}`} />
              <div className="flex-1 min-w-0">
                <div className="font-medium">{c.name}</div>
                <div className="text-sm text-gray-400 break-words">{c.detail}</div>
              </div>
              <span className={`text-xs font-medium uppercase ${STATUS[c.status].text}`}>{c.status}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
