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

export const metadata: Metadata = { title: "Application logs" };
export const dynamic = "force-dynamic";
const PATH = "/dashboard/logs";

export default async function LogsPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard("maintenance");
  if (!canAnywhere(ctx, "maintenance.diagnostics.read")) notFound();
  const { page } = parseListParams(await searchParams, ["_"] as const);
  const { events, total, jobs } = await listLogs(ctx, page);
  return (
    <>
      <PageHeader title="Application logs" description="Redacted diagnostics only: recorded activity (no details or personal data) and failed background jobs for your websites. Raw server logs live on the host." />
      <Card className="mb-4">
        <CardHeader title="Failed background jobs" />
        {jobs.length === 0 ? <EmptyState title="No failed jobs" /> : (
          <Table><thead><tr><Th>Type</Th><Th>Website</Th><Th>Attempts</Th><Th>Error</Th><Th>When</Th></tr></thead>
            <tbody>{jobs.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></tr>)}</tbody></Table>
        )}
      </Card>
      <Card>
        <CardHeader title="Recorded activity" />
        {events.length === 0 ? <EmptyState title="No activity" /> : (
          <Table><thead><tr><Th>When</Th><Th>Event</Th><Th>Type</Th><Th>Website</Th></tr></thead>
            <tbody>{events.map((e) => <tr key={e.id}><Td className="whitespace-nowrap">{formatDateTime(e.createdAt)}</Td><Td className="font-medium">{e.action}</Td><Td>{e.entityType}</Td><Td>{e.site?.name ?? "—"}</Td></tr>)}</tbody></Table>
        )}
        <Pagination page={page} total={total} buildHref={(p) => buildHref(PATH, { page: p })} />
      </Card>
    </>
  );
}
