// BEGIN CHANGE: Admin Serial Anti-Dupe Log (z_serial_antidupe_log)
"use client";

import { useCallback, useEffect, useState } from "react";
import { apiUrl } from "@/lib/api";
import { ItemIcon } from "@/components/ItemIcon";

type Row = {
  id: number;
  playerId: number;
  playerName: string;
  itemId: number;
  itemName: string;
  serial: string;
  source: string;
  createdAt: number;
};

export function AdminSerialAntidupe({ token }: { token: string }) {
  const [rows, setRows] = useState<Row[]>([]);
  const [q, setQ] = useState("");
  const [serial, setSerial] = useState("");
  const [source, setSource] = useState("");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [err, setErr] = useState("");

  const load = useCallback(async () => {
    setStatus("loading");
    setErr("");
    const qs = new URLSearchParams({ tool: "serial_antidupe_log", limit: "100" });
    if (q.trim()) qs.set("name", q.trim());
    if (serial.trim()) qs.set("serial", serial.trim());
    if (source) qs.set("source", source);
    try {
      const r = await fetch(apiUrl(`admin-panel.php?${qs.toString()}`), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao carregar log");
        setStatus("error");
        return;
      }
      setRows(json.data ?? []);
      setStatus("ok");
    } catch {
      setErr("Falha de rede");
      setStatus("error");
    }
  }, [token, q, serial, source]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-semibold">Anti-Dupe Log</h2>
        <p className="mt-1 text-sm text-muted">
          Itens removidos pelo anti-dupe de serial online (`z_serial_antidupe_log`). Source scan = poll 10s; equip = conflito ao vestir.
        </p>
      </div>

      <div className="flex flex-wrap gap-2">
        <input
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          placeholder="Nome do player"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <input
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          placeholder="Serial"
          value={serial}
          onChange={(e) => setSerial(e.target.value)}
        />
        <select
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          value={source}
          onChange={(e) => setSource(e.target.value)}
        >
          <option value="">Todas as sources</option>
          <option value="scan">scan</option>
          <option value="equip">equip</option>
        </select>
        <button
          type="button"
          className="rounded-md bg-brand px-3 py-2 text-sm text-white"
          onClick={() => void load()}
        >
          Filtrar
        </button>
      </div>

      {status === "loading" && <p className="text-sm text-muted">Carregando...</p>}
      {status === "error" && <p className="text-sm text-red-600">{err}</p>}
      {status === "ok" && rows.length === 0 && (
        <p className="text-sm text-muted">Nenhum registro ainda.</p>
      )}
      {status === "ok" && rows.length > 0 && (
        <div className="overflow-x-auto rounded-xl border border-border">
          <table className="w-full min-w-[800px] text-sm">
            <thead>
              <tr className="border-b border-border text-left text-muted">
                <th className="px-3 py-2">Data</th>
                <th className="px-3 py-2">Player</th>
                <th className="px-3 py-2">Item</th>
                <th className="px-3 py-2">Serial</th>
                <th className="px-3 py-2">Source</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.id} className="border-b border-border/50 last:border-0">
                  <td className="px-3 py-2 text-muted">
                    {r.createdAt > 0
                      ? new Date(r.createdAt * 1000).toLocaleString()
                      : "-"}
                  </td>
                  <td className="px-3 py-2 font-medium">{r.playerName}</td>
                  <td className="px-3 py-2">
                    <span className="inline-flex items-center gap-2">
                      <ItemIcon id={r.itemId} />
                      <span>
                        {r.itemName} <span className="text-muted">#{r.itemId}</span>
                      </span>
                    </span>
                  </td>
                  <td className="px-3 py-2 font-mono text-xs">{r.serial || "-"}</td>
                  <td className="px-3 py-2">{r.source}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
// END CHANGE
