"use client";
import { Fragment, useState } from "react";
import { Download, Search } from "lucide-react";
import { Badge, Button, Card, Input, PageHeader, Select, Spinner } from "@/components/ui";
import { fmtDate, useApi, useDebounced } from "@/components/hooks";

export default function AuditPage() {
  const [q, setQ] = useState("");
  const [object, setObject] = useState("");
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [user, setUser] = useState("");
  const dq = useDebounced(q);
  const qs = new URLSearchParams({ ...(dq ? { q: dq } : {}), ...(object ? { object } : {}), ...(from ? { from } : {}), ...(to ? { to } : {}), ...(user ? { user } : {}), limit: "500" }).toString();
  const logs = useApi<{ data: any[] }>(`/audit-logs?${qs}`, [qs]);
  const team = useApi<{ data: { id: string; name: string }[]; timezone: string }>("/team");
  const [open, setOpen] = useState<string | null>(null);
  const exportCsv = () => {
    const rows = (logs.data?.data ?? []).map((l) => [l.at, l.actorType, l.actorName ?? "", l.action, l.objectType, l.objectId ?? "", l.ip ?? ""].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(","));
    const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([["at,actor_type,actor,action,object_type,object_id,ip", ...rows].join("\n")], { type: "text/csv" })); a.download = "audit-log.csv"; a.click();
  };
  return (
    <>
      <PageHeader title="Audit log" subtitle="Every create, update, delete and integration action — searchable by user, object and date, retained for one year" actions={<Button icon={<Download className="h-3.5 w-3.5" />} onClick={exportCsv}>Export CSV</Button>} />
      <Card bodyClass="p-0">
        <div className="flex flex-wrap gap-2 border-b border-line/70 p-3">
          <div className="relative min-w-[200px] flex-1"><Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-3" /><Input className="pl-8" placeholder="Search actor or action" value={q} onChange={(e) => setQ(e.target.value)} /></div>
          <Select className="w-[160px]" value={user} onChange={(e) => setUser(e.target.value)}><option value="">All users</option>{team.data?.data.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</Select>
          <Select className="w-[160px]" value={object} onChange={(e) => setObject(e.target.value)}><option value="">All objects</option>{["contact", "deal", "activity", "journey", "integration", "message", "template", "form", "segment", "user", "role", "api_key", "workspace", "campaign", "ai_action", "content_post", "report"].map((o) => <option key={o}>{o}</option>)}</Select>
          <input type="date" className="field w-auto" value={from} onChange={(e) => setFrom(e.target.value)} aria-label="From" />
          <input type="date" className="field w-auto" value={to} onChange={(e) => setTo(e.target.value)} aria-label="To" />
        </div>
        {logs.loading && !logs.data ? <div className="flex justify-center py-10"><Spinner /></div> : (
          <div className="max-h-[calc(100dvh-280px)] overflow-y-auto">
            <table className="table-mac">
              <thead><tr><th>When</th><th>Actor</th><th>Action</th><th>Object</th><th>IP</th></tr></thead>
              <tbody>{logs.data?.data.map((l) => (
                <Fragment key={l.id}>
                  <tr className="cursor-pointer" onClick={() => setOpen(open === l.id ? null : l.id)}>
                    <td className="whitespace-nowrap text-ink-3">{fmtDate(l.at, team.data?.timezone)}</td>
                    <td><Badge tone={l.actorType === "user" ? "blue" : l.actorType === "agent" ? "violet" : l.actorType === "api_key" ? "amber" : "gray"}>{l.actorType}</Badge> {l.actorName}</td>
                    <td className="font-mono text-[12px]">{l.action}</td><td>{l.objectType} <span className="font-mono text-[11px] text-ink-3">{l.objectId?.slice(0, 8)}</span></td><td className="text-ink-3">{l.ip ?? "—"}</td>
                  </tr>
                  {open === l.id && (l.before || l.after) && <tr><td colSpan={5} className="bg-sunken"><div className="grid gap-2 md:grid-cols-2"><div><div className="label">Before</div><pre className="max-h-[220px] overflow-auto whitespace-pre-wrap font-mono text-[11px]">{JSON.stringify(l.before, null, 1)}</pre></div><div><div className="label">After</div><pre className="max-h-[220px] overflow-auto whitespace-pre-wrap font-mono text-[11px]">{JSON.stringify(l.after, null, 1)}</pre></div></div></td></tr>}
                </Fragment>
              ))}</tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
