import type { Metadata } from "next";
import { RetryJob } from "@/components/features/accounts";
import { Card, CardHeader, EmptyState, PageHeader, StatCard, Table, Td, Th } from "@/components/ui";
import { requireDashboard } from "@/lib/authz/guard";
import { getHealth, listFailedJobs } from "@/lib/services/platform";
import { formatDateTime } from "@/lib/utils";

export const metadata: Metadata = { title: "System health" };
export const dynamic = "force-dynamic";

export default async function HealthPage() {
  await requireDashboard("super-admin");
  const [h, failed] = await Promise.all([getHealth(), listFailedJobs()]);
  return (
    <>
      <PageHeader title="System health" description="Checked live when you open this page. There is no history: the platform does not store health metrics." />
      <div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="Database" value={h.dbOk ? "Reachable" : "Unreachable"} tone={h.dbOk ? "default" : "danger"} hint={`Round trip ${h.dbMs} ms`} />
        <StatCard label="Jobs waiting" value={h.jobs.PENDING ?? 0} tone={h.overdue ? "warning" : "default"} hint={h.overdue ? `${h.overdue} overdue by 15+ min: is the cron caller running?` : "None overdue"} />
        <StatCard label="Jobs failed (24 h)" value={h.failedRecent} tone={h.failedRecent ? "danger" : "default"} />
        <StatCard label="Locked accounts" value={h.locked} tone={h.locked ? "warning" : "default"} />
      </div>
      <Card>
        <CardHeader title="Failed background jobs" description="Error text is truncated and never includes submitted content." />
        {failed.length === 0 ? <EmptyState title="No failed jobs" /> : (
          <Table>
            <thead><tr><Th>Type</Th><Th>Website</Th><Th>Attempts</Th><Th>Last error</Th><Th>When</Th><Th><span className="sr-only">Actions</span></Th></tr></thead>
            <tbody>{failed.map((j) => <tr key={j.id}><Td>{j.type}</Td><Td>{j.site?.name ?? "—"}</Td><Td>{j.attempts}</Td><Td className="max-w-xs text-xs">{j.lastError ?? "—"}</Td><Td className="whitespace-nowrap">{formatDateTime(j.updatedAt)}</Td><Td><RetryJob jobId={j.id} /></Td></tr>)}</tbody>
          </Table>
        )}
      </Card>
    </>
  );
}
