import type { Metadata } from "next";
import Link from "next/link";
import { Badge, Card, CardHeader, EmptyState, PageHeader, StatCard, StatusBadge, Table, Td, Th, Unavailable } from "@/components/ui";
import { requireDashboard } from "@/lib/authz/guard";
import { getPlatformDashboard } from "@/lib/data/platform";
import { formatBytes, formatDateTime } from "@/lib/utils";

export const metadata: Metadata = { title: "Platform dashboard" };
export const dynamic = "force-dynamic";

export default async function SuperAdminDashboard() {
  await requireDashboard("super-admin");
  const d = await getPlatformDashboard();

  return (
    <>
      <PageHeader title="Platform overview" description="Global state of every organization and website." />

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatCard label="Organizations" value={d.organizations.total} hint={`${d.organizations.active} active · ${d.organizations.suspended} suspended`} />
        <StatCard label="Websites" value={d.sites.total} hint={`${d.sites.active} active`} />
        <StatCard label="Users" value={d.users.total} hint={`${d.users.active} active · ${d.users.suspended} suspended`} />
        <StatCard label="Storage used" value={formatBytes(d.storage.bytes)} hint={`${d.storage.files} files`} />
        <StatCard label="Open tickets" value={d.tickets.open} hint="Across all organizations" />
        <StatCard label="Critical tickets" value={d.tickets.critical} tone={d.tickets.critical > 0 ? "danger" : "default"} />
        <StatCard label="Failed jobs" value={d.failedJobs.count} tone={d.failedJobs.count > 0 ? "danger" : "default"} />
        <StatCard label="Database" value={`${d.health.dbLatencyMs} ms`} hint="Round-trip of this page's queries" />
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader
            title="Recently created organizations"
            action={<Link className="text-xs text-primary hover:underline" href="/dashboard/organizations">View all</Link>}
          />
          {d.recentOrganizations.length === 0 ? (
            <EmptyState title="No organizations yet" description="Organizations created on the platform will appear here." />
          ) : (
            <Table>
              <thead><tr><Th>Name</Th><Th>Sites</Th><Th>Status</Th><Th>Created</Th></tr></thead>
              <tbody>
                {d.recentOrganizations.map((o) => (
                  <tr key={o.id}>
                    <Td className="font-medium">{o.name}</Td>
                    <Td>{o._count.sites}</Td>
                    <Td><StatusBadge value={o.status} /></Td>
                    <Td>{formatDateTime(o.createdAt)}</Td>
                  </tr>
                ))}
              </tbody>
            </Table>
          )}
        </Card>

        <Card>
          <CardHeader
            title="Recent platform activity"
            action={<Link className="text-xs text-primary hover:underline" href="/dashboard/audit">Audit log</Link>}
          />
          {d.recentActivity.length === 0 ? (
            <EmptyState title="No activity recorded" />
          ) : (
            <ul className="divide-y divide-border">
              {d.recentActivity.map((e) => (
                <li key={e.id} className="flex items-center justify-between gap-3 px-4 py-2.5 text-sm">
                  <span>
                    <span className="font-medium">{e.action}</span>
                    <span className="text-muted-foreground"> · {e.actor?.name ?? "system"}</span>
                  </span>
                  <span className="shrink-0 text-xs text-muted-foreground">{formatDateTime(e.createdAt)}</span>
                </li>
              ))}
            </ul>
          )}
        </Card>

        <Card>
          <CardHeader title="Failed background jobs" />
          {d.failedJobs.latest.length === 0 ? (
            <EmptyState title="No failed jobs" description="Failures will appear here when background jobs run and fail." />
          ) : (
            <ul className="divide-y divide-border">
              {d.failedJobs.latest.map((j) => (
                <li key={j.id} className="px-4 py-2.5 text-sm">
                  <p className="font-medium">{j.type}</p>
                  <p className="text-xs text-muted-foreground">{j.lastError ?? "No error message"} · {formatDateTime(j.updatedAt)}</p>
                </li>
              ))}
            </ul>
          )}
        </Card>

        <Card>
          <CardHeader title="System health" />
          <ul className="divide-y divide-border text-sm">
            <li className="flex items-center justify-between px-4 py-2.5"><span>Database</span><Badge tone="success">connected</Badge></li>
            <li className="flex items-center justify-between px-4 py-2.5"><span>Integrations</span><Badge>not configured</Badge></li>
          </ul>
          <Unavailable>Uptime, queue depth and integration checks appear here once monitoring integrations are configured.</Unavailable>
        </Card>
      </div>
    </>
  );
}
