
import Link from 'next/link';
import { api, isAdmin, me } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, Empty, Forbidden, PageHeader, Pager, SearchField, Toolbar, type SP } from '@/components/ui';
import { CodeIcon, FilterIcon, HistoryIcon, XIcon } from '@/components/Icons';

type Log = { id: number; action: string; entityType: string | null; entityId: string | null; userEmail: string | null; before: unknown; after: unknown; createdAt: string };

export default async function Audit({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const user = await me();
  if (!isAdmin(user.role)) return <Forbidden what="the audit log" />;
  const qs = new URLSearchParams(Object.entries(sp).filter(([k, v]) => v && ['action', 'entityType', 'entityId', 'page'].includes(k)) as [string, string][]);
  const d = await api<{ items: Log[]; total: number; page: number; pageCount: number }>(`/admin/audit-logs?${qs}`);
  const filtered = Boolean(sp.action || sp.entityType || sp.entityId);
  return (
    <>
      <PageHeader
        title="Audit log"
        icon={<HistoryIcon className="h-5 w-5" />}
        description={
          <>
            Append-only record of admin changes, sign-ins, imports, merges and ranking runs. Secrets are redacted; IPs are stored as salted hashes. <span className="num font-semibold text-ink">{n(d.total)}</span> entries.
          </>
        }
      />
      <Toolbar>
        <SearchField name="action" defaultValue={sp.action} placeholder="Action starts with (e.g. lawyer.)" />
        <input name="entityType" defaultValue={sp.entityType} placeholder="Entity type" aria-label="Entity type" className="field w-auto max-w-40" />
        <input name="entityId" defaultValue={sp.entityId} placeholder="Entity id" aria-label="Entity id" className="field w-auto max-w-32" />
        <button className="btn btn-quiet">
          <FilterIcon className="h-4 w-4" /> Filter
        </button>
        {filtered && (
          <Link href="/audit" className="btn btn-ghost">
            <XIcon className="h-4 w-4" /> Clear
          </Link>
        )}
      </Toolbar>
      <Card>
        {d.items.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>When</th>
                  <th>Who</th>
                  <th>Action</th>
                  <th>Entity</th>
                  <th>Change</th>
                </tr>
              </thead>
              <tbody>
                {d.items.map((l) => (
                  <tr key={l.id} className="align-top">
                    <td className="whitespace-nowrap text-xs text-muted">{date(l.createdAt, true)}</td>
                    <td className="text-xs">{l.userEmail ?? <span className="text-muted">system / public</span>}</td>
                    <td>
                      <Link href={`/audit?action=${encodeURIComponent(l.action)}`} className="num rounded bg-sunken px-1.5 py-0.5 text-xs font-semibold hover:bg-ledger-soft hover:text-ledger">
                        {l.action}
                      </Link>
                    </td>
                    <td className="whitespace-nowrap text-xs">
                      {l.entityType ? (
                        <Link href={`/audit?entityType=${encodeURIComponent(l.entityType)}&entityId=${encodeURIComponent(l.entityId ?? '')}`} className="hover:text-ledger hover:underline">
                          {l.entityType} #{l.entityId}
                        </Link>
                      ) : (
                        '—'
                      )}
                    </td>
                    <td>
                      {(l.before != null || l.after != null) && (
                        <details className="text-xs">
                          <summary className="inline-flex cursor-pointer items-center gap-1 text-muted hover:text-ink">
                            <CodeIcon className="h-3.5 w-3.5" /> details
                          </summary>
                          <pre className="mt-1 max-h-72 max-w-xl overflow-auto rounded-lg bg-sunken p-2.5 text-[11px]">{JSON.stringify({ before: l.before, after: l.after }, null, 2)}</pre>
                        </details>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<HistoryIcon className="h-6 w-6" />}>No log entries match these filters.</Empty>
        )}
        <Pager page={d.page} pageCount={d.pageCount} total={d.total} href={(p) => `/audit?${new URLSearchParams({ ...Object.fromEntries(qs), page: String(p) })}`} />
      </Card>
    </>
  );
}
