"use client";

/**
 * Admin → System Health (Health Monitor)
 * ──────────────────────────────────────
 * Top section: live integration status (database, google api,
 * anthropic, smtp, twilio) — moved from the main /admin dashboard
 * so the dashboard surface can lead with platform metrics.
 * Below: heavy system rollups — table row counts, last-cron
 * timestamps, recent errors, plus an external link out to the
 * Neon dashboard for storage / connection-pool drilldowns.
 */

import { useEffect, useState } from "react";
import {
  RefreshCw, Loader2, Database, Clock, AlertTriangle, ExternalLink, Activity,
} from "lucide-react";
import HealthIndicator from "../components/health-indicator";

interface HealthData { status: string; checks: Array<{ name: string; status: string }> }
interface SystemHealth {
  tableCounts: Record<string, number>;
  totalRows: number;
  lastCronRuns: Array<{ name: string; lastRunAt: string | null; lastStatus: number | null }>;
  recentErrors: Array<{ id: string; source: string; message: string; timestamp: string; endpoint: string | null }>;
}

const NEON_CONSOLE_URL = "https://console.neon.tech";
const VERCEL_LOGS_URL = "https://vercel.com/dashboard/logs";

function formatRelative(iso: string | null): string {
  if (!iso) return "Never";
  try {
    const ms = Date.now() - new Date(iso).getTime();
    const sec = Math.floor(ms / 1000);
    if (sec < 60) return `${sec}s ago`;
    if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
    if (sec < 86_400) return `${Math.floor(sec / 3600)}h ago`;
    return `${Math.floor(sec / 86_400)}d ago`;
  } catch { return "—"; }
}

function formatNumber(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return n.toLocaleString();
}

export default function AdminHealthPage() {
  const [data, setData] = useState<HealthData | null>(null);
  const [system, setSystem] = useState<SystemHealth | null>(null);
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    Promise.all([
      fetch("/api/admin/health").then((r) => (r.ok ? r.json() : null)).catch(() => null),
      fetch("/api/admin/system-health").then((r) => (r.ok ? r.json() : null)).catch(() => null),
    ]).then(([h, s]) => {
      setData(h);
      setSystem(s);
    }).finally(() => setLoading(false));
  }
  useEffect(() => { load(); }, []);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
            <Activity className="w-5 h-5 text-slate-700" /> System Health
          </h1>
          <p className="text-slate-500 text-sm mt-1">
            Live integration status, table row counts, cron history, and recent errors.
          </p>
        </div>
        <button
          onClick={load}
          disabled={loading}
          className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-50"
        >
          {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />} Check now
        </button>
      </div>

      {/* Integration status — moved here from /admin */}
      {data && (
        <>
          <div className={`px-5 py-4 rounded-xl border text-center ${
            data.status === "healthy" ? "bg-green-50 border-green-200" : "bg-amber-50 border-amber-200"
          }`}>
            <p className={`text-lg font-bold ${data.status === "healthy" ? "text-green-700" : "text-amber-700"}`}>
              {data.status === "healthy" ? "All Systems Operational" : "Degraded Performance"}
            </p>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
            {data.checks.map((c) => (
              <HealthIndicator
                key={c.name}
                name={c.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase())}
                status={c.status}
              />
            ))}
          </div>
        </>
      )}

      {/* Table row counts */}
      {system && (
        <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
          <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
            <Database className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Database row counts</h2>
            <span className="ml-auto text-xs text-slate-500">
              {formatNumber(system.totalRows)} rows total
            </span>
            <a
              href={NEON_CONSOLE_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1 text-xs font-semibold text-brand-600 hover:underline"
            >
              Neon dashboard <ExternalLink className="w-3 h-3" />
            </a>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-px bg-slate-100">
            {Object.entries(system.tableCounts).map(([table, count]) => (
              <div key={table} className="bg-white px-4 py-3">
                <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{table}</p>
                <p className="text-lg font-bold text-slate-800 tabular-nums mt-0.5">{formatNumber(count)}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Cron jobs */}
      {system && (
        <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
          <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
            <Clock className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Cron jobs</h2>
            <span className="ml-auto text-xs text-slate-500">
              {system.lastCronRuns.filter((c) => c.lastRunAt).length} of {system.lastCronRuns.length} have run
            </span>
          </div>
          <table className="w-full text-sm">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                <th className="text-left px-4 py-3">Cron</th>
                <th className="text-right px-3 py-3">Last run</th>
                <th className="text-right px-3 py-3">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {system.lastCronRuns.map((c) => (
                <tr key={c.name}>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-700">/api/cron/{c.name}</td>
                  <td className="px-3 py-2.5 text-right text-xs text-slate-600 tabular-nums">
                    {formatRelative(c.lastRunAt)}
                  </td>
                  <td className="px-3 py-2.5 text-right">
                    {c.lastStatus == null ? (
                      <span className="text-[10px] text-slate-400">—</span>
                    ) : c.lastStatus < 400 ? (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-emerald-700">
                        {c.lastStatus} OK
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-red-700">
                        {c.lastStatus}
                      </span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="px-4 py-2 border-t border-slate-100 bg-slate-50/60 text-[11px] text-slate-500">
            Last-run timestamps come from PlatformLog rows tagged source=&quot;cron&quot;. A cron without a row hasn&apos;t logged yet — could be that it&apos;s genuinely never run, or that the handler doesn&apos;t emit a structured log.
          </div>
        </div>
      )}

      {/* Recent errors + Vercel link */}
      {system && (
        <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
          <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-500" />
            <h2 className="font-bold text-slate-800 text-sm">Recent errors</h2>
            <a
              href={VERCEL_LOGS_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="ml-auto inline-flex items-center gap-1 text-xs font-semibold text-brand-600 hover:underline"
            >
              Vercel logs <ExternalLink className="w-3 h-3" />
            </a>
          </div>
          {system.recentErrors.length === 0 ? (
            <div className="p-8 text-center text-xs text-slate-400">
              No errors logged. Either healthy or PlatformLog isn&apos;t wired into your error path yet.
            </div>
          ) : (
            <ul className="divide-y divide-slate-100">
              {system.recentErrors.map((e) => (
                <li key={e.id} className="px-4 py-2.5 flex items-start gap-3">
                  <span className="text-[10px] text-slate-400 w-24 shrink-0 tabular-nums">{formatRelative(e.timestamp)}</span>
                  <span className="text-[10px] font-bold text-slate-500 w-20 shrink-0 truncate">{e.source}</span>
                  <span className="text-xs text-slate-700 flex-1 truncate">{e.message}</span>
                  {e.endpoint && (
                    <span className="text-[10px] text-slate-400 font-mono truncate max-w-[200px]">{e.endpoint}</span>
                  )}
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}
