"use client";

import { useEffect, useState } from "react";
import { Search } from "lucide-react";
import { Input, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { Pager } from "@/components/admin/common";
import { qs } from "@/lib/api";
import { formatDateTime } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Entry {
  id: number;
  action: string;
  user_name: string | null;
  organization_name: string | null;
  subject_type: string | null;
  subject_id: number | null;
  meta: Record<string, unknown> | null;
  ip: string | null;
  created_at: string;
}

export default function AuditPage() {
  const [term, setTerm] = useState("");
  const [action, setAction] = useState("");
  const [page, setPage] = useState(1);
  useEffect(() => {
    const t = setTimeout(() => setAction(term.trim()), 300);
    return () => clearTimeout(t);
  }, [term]);
  const { data } = useApi<{ data: Entry[]; meta: { total: number; last_page: number } }>(`/admin/audit${qs({ action, page })}`);
  return (
    <>
      <PageHeader title="Audit log" description="Who changed what, across every workspace. Entries can't be edited or deleted." />
      <div className="relative mb-4 md:w-80">
        <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
        <Input aria-label="Filter by action" placeholder="Action starts with, e.g. platform. or billing." className="w-full pl-9" value={term} onChange={(e) => (setTerm(e.target.value), setPage(1))} />
      </div>
      <Panel>
        {!data ? (
          <Skeleton className="m-5 h-40" />
        ) : (
          <>
            <div className="relative overflow-x-auto">
              <table className="w-full min-w-[820px] text-sm">
                <thead className="border-b border-line text-left text-[13px] text-muted">
                  <tr>
                    <th className="px-5 py-3 font-medium">When</th>
                    <th className="px-3 py-3 font-medium">Who</th>
                    <th className="px-3 py-3 font-medium">Workspace</th>
                    <th className="px-3 py-3 font-medium">Action</th>
                    <th className="px-5 py-3 font-medium">Details</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line">
                  {data.data.map((e) => (
                    <tr key={e.id}>
                      <td className="tabular whitespace-nowrap px-5 py-2.5 text-muted">{formatDateTime(e.created_at)}</td>
                      <td className="px-3 py-2.5">{e.user_name ?? "System"}</td>
                      <td className="px-3 py-2.5 text-muted">{e.organization_name ?? "—"}</td>
                      <td className="px-3 py-2.5 font-mono text-[12.5px]">{e.action}</td>
                      <td className="max-w-[320px] truncate px-5 py-2.5 text-[13px] text-muted" title={e.meta ? JSON.stringify(e.meta) : undefined}>
                        {e.subject_type ? `${e.subject_type} #${e.subject_id}` : ""}
                        {e.meta ? ` ${JSON.stringify(e.meta)}` : ""}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pager page={page} last={data.meta.last_page} total={data.meta.total} onPage={setPage} />
          </>
        )}
      </Panel>
    </>
  );
}
