// BEGIN CHANGE: audit log UI (admin >= 6)
"use client";

import { useEffect, useState } from "react";
import { apiUrl } from "@/lib/api";
import { fmtTs } from "./types";

type AuditRow = {
  id: number;
  adminId: number;
  adminName: string;
  action: string;
  targetAccountId: number | null;
  targetPlayerId: number | null;
  targetLabel: string;
  detail: Record<string, unknown> | null;
  ip: string;
  createdAt: number;
};

export function AdminAuditPanel({
  token,
  labels,
}: {
  token: string;
  labels: { loading: string; failed: string; refresh: string; denied: string; title: string };
}) {
  const [rows, setRows] = useState<AuditRow[]>([]);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  async function load() {
    setBusy(true);
    setErr("");
    try {
      const r = await fetch(apiUrl("admin-panel.php?tool=audit&limit=100"), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (r.status === 403) {
        setErr(labels.denied);
        return;
      }
      if (!r.ok) throw new Error(json.error || "fail");
      setRows(json.data || []);
    } catch {
      setErr(labels.failed);
    } finally {
      setBusy(false);
    }
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2">
        <h2 className="text-xl font-semibold">{labels.title}</h2>
        <button
          type="button"
          disabled={busy}
          onClick={load}
          className="rounded-md border border-border px-3 py-1.5 text-sm disabled:opacity-50"
        >
          {labels.refresh}
        </button>
      </div>
      {err && <p className="text-sm text-red-400">{err}</p>}
      <div className="max-h-[28rem] overflow-auto rounded-xl border border-border bg-panel">
        <table className="w-full text-left text-sm">
          <thead className="sticky top-0 bg-panel text-muted">
            <tr>
              <th className="px-3 py-2">Quando</th>
              <th className="px-3 py-2">Admin</th>
              <th className="px-3 py-2">Acao</th>
              <th className="px-3 py-2">Alvo</th>
              <th className="px-3 py-2">IP</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.id} className="border-t border-border/40">
                <td className="px-3 py-2 whitespace-nowrap">{fmtTs(r.createdAt)}</td>
                <td className="px-3 py-2">
                  {r.adminName} #{r.adminId}
                </td>
                <td className="px-3 py-2 font-mono text-xs">{r.action}</td>
                <td className="px-3 py-2">
                  {r.targetLabel || "-"}
                  {r.targetAccountId ? ` (acc ${r.targetAccountId})` : ""}
                </td>
                <td className="px-3 py-2 font-mono text-xs">{r.ip || "-"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
// END CHANGE
