import { ChevronRight } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { formatDateTime, formatRelativeTime } from "@/lib/format";
import type { AuditLogRow } from "@/lib/queries/admin";

type Tone = "neutral" | "brand" | "success" | "warning" | "danger" | "info" | "outline";

/** Colour an audit action by its lifecycle suffix. */
function auditActionTone(action: string): Tone {
  if (action === "LOGIN_FAILED" || action.endsWith("_THROTTLED")) return "warning";
  if (action.endsWith("_CREATED")) return "success";
  if (action.endsWith("_UPDATED")) return "info";
  if (action.endsWith("_DELETED")) return "danger";
  return "neutral";
}

/**
 * Audit trail table.
 *
 * Each row carries its own `<details>` disclosure for the metadata payload so
 * the JSON is inspectable without leaving the page.
 */
export function AuditTable({ rows }: { rows: AuditLogRow[] }) {
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Waktu</TableHead>
          <TableHead>Pelaku</TableHead>
          <TableHead>Aksi</TableHead>
          <TableHead>Entitas</TableHead>
          <TableHead>Alamat IP</TableHead>
          <TableHead className="text-right">Detail</TableHead>
        </TableRow>
      </TableHeader>

      <TableBody>
        {rows.map((log) => (
          <TableRow key={log.id}>
            <TableCell className="whitespace-nowrap">
              <span className="block text-xs font-medium text-primary">
                {formatRelativeTime(log.createdAt)}
              </span>
              <span className="block text-xs text-tertiary">{formatDateTime(log.createdAt)}</span>
            </TableCell>

            <TableCell>
              {log.actorName ? (
                <div className="flex items-center gap-2">
                  <Avatar name={log.actorName} size="xs" />
                  <div className="min-w-0">
                    <span className="block truncate text-sm text-primary">{log.actorName}</span>
                    <span className="block truncate text-xs text-tertiary">@{log.actorUsername}</span>
                  </div>
                </div>
              ) : (
                <span className="text-xs text-tertiary">Sistem</span>
              )}
            </TableCell>

            <TableCell>
              <Badge variant={auditActionTone(log.action)}>{log.action}</Badge>
            </TableCell>

            <TableCell className="text-xs">
              {log.entity ? (
                <>
                  <span className="block text-primary">{log.entity}</span>
                  {log.entityId ? (
                    <span className="block truncate text-tertiary">{log.entityId}</span>
                  ) : null}
                </>
              ) : (
                "—"
              )}
            </TableCell>

            <TableCell className="whitespace-nowrap text-xs text-tertiary">
              {log.ipAddress ?? "—"}
            </TableCell>

            <TableCell className="text-right">
              {log.metadata ? <MetadataDisclosure metadata={log.metadata} /> : <span className="text-xs text-tertiary">—</span>}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

function MetadataDisclosure({ metadata }: { metadata: unknown }) {
  return (
    <details className="group inline-block text-left">
      <summary className="inline-flex cursor-pointer list-none items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-brand-600 transition-colors hover:bg-hover dark:text-brand-200">
        <ChevronRight className="size-3.5 transition-transform group-open:rotate-90" />
        Lihat
      </summary>
      <pre className="mt-2 max-h-72 max-w-md overflow-auto rounded-lg border border-subtle bg-sunken p-3 text-left text-[11px] leading-relaxed text-secondary">
        {JSON.stringify(metadata, null, 2)}
      </pre>
    </details>
  );
}
