import type { Metadata } from "next";
import { FilterBar } from "@/components/features";
import { Card, EmptyState, PageHeader, Pagination, Table, Td, Th } from "@/components/ui";
import { requireDashboard } from "@/lib/authz/guard";
import { listAuditLogs } from "@/lib/data/lists";
import { buildHref, parseListParams } from "@/lib/list-params";
import { formatDateTime } from "@/lib/utils";
import { notFound } from "next/navigation";
import { canAnywhere } from "@/lib/authz/context";

export const metadata: Metadata = { title: "Audit log" };
export const dynamic = "force-dynamic";

const PATH = "/dashboard/audit";

export default async function AuditPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard("admin");
  if (!canAnywhere(ctx, "audit.read")) notFound();
  const { q, page } = parseListParams(await searchParams, ["_"] as const);
  const { rows, total } = await listAuditLogs(ctx, { q, page });

  return (
    <>
      <PageHeader title="Audit log" description="Activity within your organizations and sites." />
      <Card>
        <FilterBar action={PATH} q={q} placeholder="Filter by action, e.g. auth.login" />
        {rows.length === 0 ? (
          <EmptyState title="No events found" />
        ) : (
          <Table>
            <thead><tr><Th>When</Th><Th>Action</Th><Th>Actor</Th><Th>Entity</Th><Th>Organization</Th><Th>Site</Th></tr></thead>
            <tbody>
              {rows.map((e) => (
                <tr key={e.id}>
                  <Td className="whitespace-nowrap">{formatDateTime(e.createdAt)}</Td>
                  <Td className="font-medium">{e.action}</Td>
                  <Td>{e.actor?.name ?? "system"}</Td>
                  <Td>{e.entityType}</Td>
                  <Td>{e.organization?.name ?? "—"}</Td>
                  <Td>{e.site?.name ?? "—"}</Td>
                </tr>
              ))}
            </tbody>
          </Table>
        )}
        <Pagination page={page} total={total} buildHref={(p) => buildHref(PATH, { q, page: p })} />
      </Card>
    </>
  );
}
