"use client";

import { useEffect, useMemo, useState } from "react";
import { get } from "@/lib/api";
import { Notice, Spinner } from "@/components/ui";
import { DataGrid, type ColDef } from "@/components/DataGrid";

type Entry = {
  id: number;
  actor: string;
  target: string;
  action: string;
  before: unknown;
  after: unknown;
  occurredAt: string;
};

function fmt(v: unknown): string {
  if (v === null || v === undefined) return "∅";
  if (typeof v === "object") return JSON.stringify(v);
  return String(v);
}

export default function AuditPanel() {
  const [entries, setEntries] = useState<Entry[] | null>(null);
  const [target, setTarget] = useState("");
  const [actor, setActor] = useState("");
  const [error, setError] = useState<string | null>(null);

  async function load() {
    try {
      const q = new URLSearchParams();
      if (target) q.set("target", target);
      if (actor) q.set("actor", actor);
      const d = await get<{ entries: Entry[] }>(`audit-log?${q.toString()}`);
      setEntries(d.entries);
    } catch (e) {
      setError((e as Error).message);
    }
  }
  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const rowData = useMemo(
    () =>
      (entries ?? []).map((e) => ({
        when: new Date(e.occurredAt).toLocaleString(),
        actor: e.actor,
        target: e.target,
        action: e.action,
        before: fmt(e.before),
        after: fmt(e.after),
      })),
    [entries],
  );

  const columnDefs: ColDef[] = [
    { field: "when", headerName: "When", width: 180, filter: false },
    { field: "actor", headerName: "Actor", width: 180 },
    { field: "target", headerName: "Target", flex: 1, minWidth: 150 },
    { field: "action", headerName: "Action", width: 130 },
    { field: "before", headerName: "Before", flex: 1, minWidth: 160, tooltipField: "before" },
    { field: "after", headerName: "After", flex: 1, minWidth: 160, tooltipField: "after" },
  ];

  if (error) return <Notice kind="error">Could not load audit log: {error}</Notice>;

  return (
    <>
      <p className="mb-3 text-sm text-slate-600">
        Every Admin Backoffice change and kill-switch action — who, what, before and after — newest first.
      </p>

      <form
        className="card mb-4 flex flex-wrap items-end gap-3"
        onSubmit={(e) => {
          e.preventDefault();
          load();
        }}
      >
        <div>
          <label htmlFor="f-target" className="label">Target prefix</label>
          <input id="f-target" value={target} onChange={(e) => setTarget(e.target.value)} placeholder="settings." className="input" />
        </div>
        <div>
          <label htmlFor="f-actor" className="label">Actor</label>
          <input id="f-actor" value={actor} onChange={(e) => setActor(e.target.value)} placeholder="jane@digt.ch" className="input" />
        </div>
        <button type="submit" className="btn-secondary">Filter</button>
      </form>

      {!entries ? <Spinner label="Loading audit log…" /> : <DataGrid rowData={rowData} columnDefs={columnDefs} height={560} />}
    </>
  );
}
