import { api } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, Kpi, PageHeader, Pill } from '@/components/ui';
import { ActivityIcon, AlertIcon, ChartIcon, DatabaseIcon, LayersIcon, ServerIcon } from '@/components/Icons';

type H = {
  status: string;
  uptimeSec: number;
  memoryMb: number;
  node: string;
  database: { latencyMs: number; size: string; connections: number };
  queue: { redis: boolean; counts: Record<string, Record<string, number>> | null };
  recentRankingRuns: { id: number; status: string; finishedAt: string | null; error: string | null }[];
  failedRankingRuns7d: number;
  lastSeoEvaluation: string | null;
  environment: string;
  storage: { backend: string; status: string };
  email: { configured: boolean; stats: { last_sent: string | null; last_failed: string | null } };
  workers: { name: string; status: string; lastSuccessAt: string | null; lastFailureAt: string | null }[];
  stripeWebhook: { last_received: string | null; last_processed: string | null; failed_24h: number };
  backup: { configured: boolean; note: string };
};

function uptime(sec: number) {
  const d = Math.floor(sec / 86400);
  const h = Math.floor((sec % 86400) / 3600);
  const m = Math.floor((sec % 3600) / 60);
  return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m`;
}

export default async function Health() {
  const h = await api<H>('/admin/health');
  return (
    <>
      <PageHeader title="System health" icon={<ActivityIcon className="h-5 w-5" />} description={`Environment: ${h.environment} · Node ${h.node}`} />
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <Kpi label="API" icon={<ServerIcon className="h-4 w-4" />} value={<Pill value={h.status} tone={['error', 'down', 'degraded'].includes(h.status) ? 'bad' : 'good'} />} hint={`up ${uptime(h.uptimeSec)} · ${n(h.memoryMb)} MB`} />
        <Kpi label="Database latency" icon={<DatabaseIcon className="h-4 w-4" />} tone={h.database.latencyMs > 100 ? 'warn' : 'default'} value={`${h.database.latencyMs} ms`} hint={`${h.database.size} · ${h.database.connections} connections`} />
        <Kpi label="Job queue" icon={<LayersIcon className="h-4 w-4" />} tone={h.queue.redis ? 'default' : 'warn'} value={<Pill value={h.queue.redis ? 'redis' : 'inline'} tone={h.queue.redis ? 'good' : 'warn'} />} hint={h.queue.redis ? 'BullMQ workers' : 'jobs run inside the API'} />
        <Kpi label="Failed ranking runs" icon={<AlertIcon className="h-4 w-4" />} tone={h.failedRankingRuns7d ? 'warn' : 'default'} value={h.failedRankingRuns7d} hint="last 7 days" />
      </div>
      <Card title="Worker and integration health" className="mt-6">
        <table className="tbl"><thead><tr><th>Worker</th><th>Status</th><th>Last successful job</th><th>Last failure</th></tr></thead>
          <tbody>{h.workers.map((w) => <tr key={w.name}><td>{w.name}</td><td><Pill value={w.status} /></td><td>{date(w.lastSuccessAt, true)}</td><td>{date(w.lastFailureAt, true)}</td></tr>)}</tbody>
        </table>
        <div className="space-y-1 border-t border-rule p-4 text-sm">
          <p>Email: {h.email.configured ? 'configured' : 'not configured'}; last delivery {date(h.email.stats.last_sent, true)}</p>
          <p>Storage: {h.storage.backend} / {h.storage.status}</p>
          <p>Stripe webhook: last processed {date(h.stripeWebhook.last_processed, true)}; {h.stripeWebhook.failed_24h} failures in 24 hours</p>
          <p>Backup: {h.backup.note}</p>
        </div>
      </Card>
      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        <Card title="Queues" icon={<LayersIcon className="h-4 w-4" />}>
          {h.queue.counts ? (
            <table className="tbl">
              <thead>
                <tr>
                  <th>Queue</th>
                  <th className="text-right">Waiting</th>
                  <th className="text-right">Active</th>
                  <th className="text-right">Completed</th>
                  <th className="text-right">Failed</th>
                </tr>
              </thead>
              <tbody>
                {Object.entries(h.queue.counts).map(([q, c]) => (
                  <tr key={q}>
                    <td className="num font-medium">{q}</td>
                    <td className="num text-right">{n(c.waiting ?? 0)}</td>
                    <td className="num text-right">{n(c.active ?? 0)}</td>
                    <td className="num text-right text-muted">{n(c.completed ?? 0)}</td>
                    <td className={`num text-right ${c.failed ? 'font-semibold text-danger' : 'text-muted'}`}>{n(c.failed ?? 0)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="p-4 text-sm text-muted">Redis is not connected; background jobs run inline.</p>
          )}
        </Card>
        <Card title="Recent ranking runs" icon={<ChartIcon className="h-4 w-4" />}>
          {h.recentRankingRuns.length ? (
            <table className="tbl">
              <tbody>
                {h.recentRankingRuns.map((r) => (
                  <tr key={r.id}>
                    <td className="num font-semibold">#{r.id}</td>
                    <td>
                      <Pill value={r.status} />
                    </td>
                    <td className="whitespace-nowrap">{date(r.finishedAt, true)}</td>
                    <td className="text-xs text-danger">{r.error}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="p-4 text-sm text-muted">No runs yet.</p>
          )}
          <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Last SEO evaluation: {date(h.lastSeoEvaluation, true)}</p>
        </Card>
      </div>
    </>
  );
}
