"use client";

import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ChevronDown, ChevronRight, ScrollText, ShieldCheck } from "lucide-react";
import { useState } from "react";
import { PageHeader } from "@/components/page-header";
import { Badge, Button, EmptyState, Mono, Panel, PageLoader } from "@/components/ui";
import { api } from "@/lib/api";
import { formatTime } from "@/lib/utils";

const PAGE_SIZE = 25;

function actorLabel(actor: string): string {
  if (actor.startsWith("user:")) return "user";
  if (actor.startsWith("apikey:")) return "api key";
  if (actor.startsWith("agent:")) return "agent";
  if (actor.startsWith("workflow:")) return "workflow";
  return actor;
}

function Detail({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="grid grid-cols-[92px_1fr] gap-3 py-1.5">
      <span className="eyebrow pt-0.5">{label}</span>
      <div className="min-w-0 text-xs text-muted">{children}</div>
    </div>
  );
}

export default function AuditPage() {
  const [page, setPage] = useState(0);
  const [openId, setOpenId] = useState<string | null>(null);

  const audit = useQuery({
    queryKey: ["audit", page],
    queryFn: () => api.listAudit(PAGE_SIZE, page * PAGE_SIZE),
    placeholderData: keepPreviousData,
  });

  const rows = audit.data ?? [];
  const hasNext = rows.length === PAGE_SIZE;
  const go = (next: number) => {
    setOpenId(null);
    setPage(next);
  };

  return (
    <div>
      <PageHeader
        eyebrow="Govern"
        title="Audit log"
        description="An append-only, hash-chained record of every privileged action."
        actions={
          <span className="flex items-center gap-1.5 text-xs text-success">
            <ShieldCheck className="h-4 w-4" /> tamper-evident
          </span>
        }
      />

      {audit.isLoading ? (
        <PageLoader />
      ) : page === 0 && rows.length === 0 ? (
        <EmptyState icon={<ScrollText className="h-8 w-8" />} title="No audit entries yet" />
      ) : (
        <>
          <Panel className="p-0">
            <div className="divide-y divide-line">
              {rows.map((e) => {
                const open = openId === e.id;
                return (
                  <div key={e.id}>
                    <button
                      onClick={() => setOpenId(open ? null : e.id)}
                      className="flex w-full items-center gap-4 px-5 py-3 text-left transition-colors hover:bg-surface-2/40"
                    >
                      {open ? (
                        <ChevronDown className="h-4 w-4 shrink-0 text-faint" />
                      ) : (
                        <ChevronRight className="h-4 w-4 shrink-0 text-faint" />
                      )}
                      <span className="w-10 shrink-0 font-mono text-xs text-faint">#{e.seq}</span>
                      <Badge tone="accent">{e.action}</Badge>
                      <span className="text-sm text-muted">{actorLabel(e.actor)}</span>
                      {e.target && (
                        <Mono className="hidden text-faint sm:block">{e.target.slice(0, 12)}</Mono>
                      )}
                      <div className="flex-1" />
                      <span className="hidden font-mono text-[11px] text-faint md:block">
                        {e.hash.slice(0, 10)}…
                      </span>
                      <span className="text-xs text-faint">{formatTime(e.created_at)}</span>
                    </button>
                    {open && (
                      <div className="border-t border-line bg-ink/40 px-5 py-4 sm:pl-14">
                        <div className="grid gap-x-6 md:grid-cols-2">
                          <div>
                            <Detail label="Actor">
                              <span className="break-all font-mono text-fg">{e.actor}</span>
                            </Detail>
                            <Detail label="Action">
                              <span className="font-mono text-fg">{e.action}</span>
                            </Detail>
                            <Detail label="Target">
                              {e.target ? (
                                <span className="break-all font-mono text-fg">{e.target}</span>
                              ) : (
                                <span className="text-faint">-</span>
                              )}
                            </Detail>
                            <Detail label="Time">
                              <span className="text-fg">
                                {new Date(e.created_at).toLocaleString()}
                              </span>
                            </Detail>
                          </div>
                          <div>
                            <Detail label="Hash">
                              <span className="break-all font-mono text-[11px] text-success">
                                {e.hash}
                              </span>
                            </Detail>
                            <Detail label="Prev hash">
                              {e.hash_prev ? (
                                <span className="break-all font-mono text-[11px] text-faint">
                                  {e.hash_prev}
                                </span>
                              ) : (
                                <span className="text-faint">none (chain root)</span>
                              )}
                            </Detail>
                          </div>
                        </div>
                        <div className="mt-2">
                          <span className="eyebrow">Metadata</span>
                          <pre className="mt-1.5 overflow-x-auto rounded-lg border border-line bg-ink/60 p-3 font-mono text-[11px] leading-relaxed text-muted">
                            {Object.keys(e.metadata ?? {}).length
                              ? JSON.stringify(e.metadata, null, 2)
                              : "{}"}
                          </pre>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </Panel>

          <div className="mt-4 flex items-center justify-between">
            <span className="text-xs text-faint">
              {rows.length > 0
                ? `Showing ${page * PAGE_SIZE + 1}–${page * PAGE_SIZE + rows.length}`
                : "No more entries"}
            </span>
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                variant="outline"
                disabled={page === 0 || audit.isFetching}
                onClick={() => go(page - 1)}
              >
                Previous
              </Button>
              <span className="font-mono text-xs text-muted">Page {page + 1}</span>
              <Button
                size="sm"
                variant="outline"
                disabled={!hasNext || audit.isFetching}
                onClick={() => go(page + 1)}
              >
                Next
              </Button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
