// app/admin/auditoria/page.tsx
// Read-only viewer over the append-only audit_log (admin.md accountability). Shows
// who did what and when: logins, unmasks, exports, refunds, config changes, draw
// commit/reveal, manual entries. Filter by entity, paginated. viewer+ (the trail
// carries actions + identity hashes, not raw PII).

import * as React from "react";
import { redirect } from "next/navigation";
import { requireRole, AuthError } from "@/lib/auth";
import { getAuditLog } from "@/app/admin/_lib/queries";
import { AdminPagination } from "@/components/admin/AdminPagination";
import { Card } from "@/components/ui";

export const dynamic = "force-dynamic";

const mono: React.CSSProperties = {
  fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
};

export default async function AuditLogPage({
  searchParams,
}: {
  searchParams: Promise<{ entity?: string; offset?: string }>;
}) {
  try {
    await requireRole("viewer");
  } catch (err) {
    if (err instanceof AuthError) redirect("/admin/login");
    throw err;
  }

  const sp = await searchParams;
  const entity = sp.entity?.trim() || undefined;
  const pageSize = 50;
  const offset = Math.max(parseInt(sp.offset ?? "0", 10) || 0, 0);

  const fetched = await getAuditLog({ entity, limit: pageSize + 1, offset });
  const hasNext = fetched.length > pageSize;
  const rows = hasNext ? fetched.slice(0, pageSize) : fetched;

  return (
    <div className="flex flex-col gap-lg">
      <h1 className="font-impact text-heading-lg font-bold text-ink-strong">
        Auditoría
      </h1>
      <p className="font-body text-body-md text-muted">
        Registro append-only de todas las acciones sensibles: quién hizo qué y
        cuándo (ingresos, revelaciones de datos, exportaciones, reembolsos, cambios
        de configuración, sorteo, entradas manuales).
      </p>

      <form method="get" className="flex flex-wrap items-end gap-3">
        <div className="flex flex-col gap-1.5">
          <label
            htmlFor="entity"
            className="font-body text-body-md font-medium text-ink-strong"
          >
            Filtrar por entidad
          </label>
          <input
            id="entity"
            name="entity"
            type="search"
            defaultValue={entity ?? ""}
            placeholder="purchase, raffle, export, admin_session, draw..."
            className="min-h-11 w-80 rounded-md border border-track bg-canvas px-4 font-body text-body-md text-ink-strong focus-visible:outline focus-visible:outline-[3px] focus-visible:outline-offset-1 focus-visible:outline-steelblue"
          />
        </div>
        <button
          type="submit"
          className="min-h-11 rounded-md border border-primary px-5 font-body text-body-md font-bold text-primary hover:bg-primary hover:text-on-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
        >
          Filtrar
        </button>
      </form>

      <Card elevation="tight" className="p-lg">
        {rows.length === 0 ? (
          <p className="font-body text-body-md text-muted">
            No hay registros{entity ? ` para "${entity}"` : ""}.
          </p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-left">
              <thead>
                <tr className="border-b border-hairline">
                  <Th>Fecha (Perú)</Th>
                  <Th>Entidad</Th>
                  <Th>Acción</Th>
                  <Th>Actor</Th>
                  <Th>Detalle</Th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr
                    key={r.id}
                    className="border-b border-hairline align-top last:border-0"
                  >
                    <Td>
                      {new Date(r.at).toLocaleString("es-PE", {
                        timeZone: "America/Lima",
                      })}
                    </Td>
                    <Td>{r.entity}</Td>
                    <Td>{r.action}</Td>
                    <Td>{r.actor}</Td>
                    <Td>
                      <span
                        className="block max-w-[520px] break-words text-caption text-muted"
                        style={mono}
                      >
                        {r.detail ? JSON.stringify(r.detail) : ""}
                      </span>
                    </Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <AdminPagination
        basePath="/admin/auditoria"
        params={{ ...(entity ? { entity } : {}) }}
        offset={offset}
        pageSize={pageSize}
        shown={rows.length}
        hasNext={hasNext}
      />
    </div>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th
      scope="col"
      className="py-2 pr-4 font-body text-caption font-medium text-muted-label"
    >
      {children}
    </th>
  );
}
function Td({ children }: { children: React.ReactNode }) {
  return (
    <td className="py-2 pr-4 font-body text-body-sm text-ink-strong">
      {children}
    </td>
  );
}
