// BEGIN CHANGE: Admin Jackpot Log (z_jackpot_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;
  quantity: number;
  tier: string;
  usesBefore: number;
  source: string;
  createdAt: number;
};

export function AdminJackpot({ token }: { token: string }) {
  const [rows, setRows] = useState<Row[]>([]);
  const [q, setQ] = useState("");
  const [tier, setTier] = 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: "jackpot_log", limit: "80" });
    if (q.trim()) qs.set("name", q.trim());
    if (tier) qs.set("tier", tier);
    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, tier]);

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

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-semibold">Jackpot Log</h2>
        <p className="mt-1 text-sm text-muted">
          Aberturas de Premium Box / surprise bags (`z_jackpot_log`). Regras internas de peso nao sao publicas.
        </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)}
        />
        <select
          className="rounded-md border border-border bg-background px-3 py-2 text-sm"
          value={tier}
          onChange={(e) => setTier(e.target.value)}
        >
          <option value="">Todos os tiers</option>
          <option value="S">S</option>
          <option value="A">A</option>
          <option value="B">B</option>
          <option value="C">C</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-[720px] 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">Tier</th>
                <th className="px-3 py-2">Item</th>
                <th className="px-3 py-2">Source</th>
                <th className="px-3 py-2 text-right">Uses</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">{r.tier}</td>
                  <td className="px-3 py-2">
                    <div className="flex items-center gap-2">
                      {r.itemId > 0 && <ItemIcon id={r.itemId} size={28} alt={r.itemName} />}
                      <span>
                        {r.quantity}x {r.itemName}
                      </span>
                    </div>
                  </td>
                  <td className="px-3 py-2 text-muted">{r.source}</td>
                  <td className="px-3 py-2 text-right">{r.usesBefore}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
// END CHANGE
