// BEGIN CHANGE: tools - house items + orphan scan + player/account trace
"use client";

import { FormEvent, useState } from "react";
import { apiUrl } from "@/lib/api";
import { AdminConfirmModal } from "./AdminConfirmModal";

type OrphanRow = { table: string; kind: string; count: number };

export function AdminTools({
  token,
  labels,
}: {
  token: string;
  labels: {
    title: string;
    houseHint: string;
    playerName: string;
    search: string;
    failed: string;
    loading: string;
  };
}) {
  const [name, setName] = useState("");
  const [data, setData] = useState<Record<string, unknown> | null>(null);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  const [traceName, setTraceName] = useState("");
  const [traceAccount, setTraceAccount] = useState("");
  const [traceData, setTraceData] = useState<Record<string, unknown> | null>(null);
  const [traceErr, setTraceErr] = useState("");
  const [traceBusy, setTraceBusy] = useState(false);

  const [orphans, setOrphans] = useState<OrphanRow[] | null>(null);
  const [orphanMeta, setOrphanMeta] = useState<{
    orphanTotal: number;
    orphanGroups: number;
    note?: string;
  } | null>(null);
  const [orphanErr, setOrphanErr] = useState("");
  const [orphanBusy, setOrphanBusy] = useState(false);
  // BEGIN CHANGE: item 6 - acao de tratar/excluir orfaos (com confirmacao + senha admin)
  const [orphanMsg, setOrphanMsg] = useState("");
  const [pendingOrphan, setPendingOrphan] = useState<OrphanRow | null>(null);

  async function runOrphanDelete(
    row: OrphanRow,
    adminPassword: string,
    confirm: string,
  ) {
    setOrphanBusy(true);
    setOrphanErr("");
    setOrphanMsg("");
    try {
      const r = await fetch(apiUrl("admin-panel.php"), {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          action: "orphan_delete",
          table: row.table,
          kind: row.kind,
          confirm,
          adminPassword,
        }),
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setOrphanErr(json.error || labels.failed);
        return;
      }
      setOrphanMsg(json.note || "OK");
      await onOrphanScan();
    } catch {
      setOrphanErr(labels.failed);
    } finally {
      setOrphanBusy(false);
    }
  }
  // END CHANGE

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setErr("");
    setData(null);
    try {
      const r = await fetch(
        apiUrl(`admin-panel.php?tool=house_items&name=${encodeURIComponent(name.trim())}`),
        { headers: { Authorization: `Bearer ${token}` } },
      );
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || labels.failed);
        return;
      }
      setData(json.data);
    } catch {
      setErr(labels.failed);
    } finally {
      setBusy(false);
    }
  }

  async function onTrace(e: FormEvent) {
    e.preventDefault();
    setTraceBusy(true);
    setTraceErr("");
    setTraceData(null);
    try {
      const qs = new URLSearchParams();
      qs.set("tool", "player_trace");
      if (traceName.trim()) qs.set("name", traceName.trim());
      if (traceAccount.trim()) qs.set("account", traceAccount.trim());
      const r = await fetch(apiUrl(`admin-panel.php?${qs.toString()}`), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setTraceErr(json.error || labels.failed);
        return;
      }
      setTraceData(json.data);
    } catch {
      setTraceErr(labels.failed);
    } finally {
      setTraceBusy(false);
    }
  }

  async function onOrphanScan() {
    setOrphanBusy(true);
    setOrphanErr("");
    setOrphans(null);
    setOrphanMeta(null);
    try {
      const r = await fetch(apiUrl("admin-panel.php?tool=orphan_scan"), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setOrphanErr(json.error || labels.failed);
        return;
      }
      const d = json.data || {};
      setOrphans((d.orphans || []) as OrphanRow[]);
      setOrphanMeta({
        orphanTotal: Number(d.orphanTotal || 0),
        orphanGroups: Number(d.orphanGroups || 0),
        note: d.note,
      });
    } catch {
      setOrphanErr(labels.failed);
    } finally {
      setOrphanBusy(false);
    }
  }

  return (
    <div className="space-y-8">
      <div className="space-y-4">
        <h2 className="text-xl font-semibold">{labels.title}</h2>
        <p className="text-sm text-muted">{labels.houseHint}</p>
        <form onSubmit={onSubmit} className="flex flex-wrap gap-2">
          <input
            className="min-w-[220px] flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm"
            placeholder={labels.playerName}
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <button
            type="submit"
            disabled={busy}
            className="rounded-md bg-brand px-4 py-2 text-sm text-background disabled:opacity-50"
          >
            {busy ? labels.loading : labels.search}
          </button>
        </form>
        {err && <p className="text-sm text-red-400">{err}</p>}
        {data && (
          <pre className="max-h-96 overflow-auto rounded-xl border border-border bg-panel p-4 text-xs">
            {JSON.stringify(data, null, 2)}
          </pre>
        )}
      </div>

      <div className="space-y-4 rounded-xl border border-border bg-panel p-4">
        <h3 className="text-lg font-semibold">Rastreio pos-delete</h3>
        <p className="text-sm text-muted">
          Busca shop history, doacoes, lottery, fila shop e outros rastros por nome do char e/ou conta
          (mesmo se ja foram excluidos).
        </p>
        <form onSubmit={onTrace} className="flex flex-wrap gap-2">
          <input
            className="min-w-[180px] flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm"
            placeholder="Nome do personagem"
            value={traceName}
            onChange={(e) => setTraceName(e.target.value)}
          />
          <input
            className="min-w-[180px] flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm"
            placeholder="Nome da conta"
            value={traceAccount}
            onChange={(e) => setTraceAccount(e.target.value)}
          />
          <button
            type="submit"
            disabled={traceBusy}
            className="rounded-md bg-brand px-4 py-2 text-sm text-background disabled:opacity-50"
          >
            {traceBusy ? labels.loading : "Rastrear"}
          </button>
        </form>
        {traceErr && <p className="text-sm text-red-400">{traceErr}</p>}
        {traceData && (
          <div className="space-y-2">
            <pre className="max-h-[28rem] overflow-auto rounded-md border border-border bg-background p-3 text-xs">
              {JSON.stringify(traceData, null, 2)}
            </pre>
          </div>
        )}
      </div>

      <div className="space-y-4 rounded-xl border border-border bg-panel p-4">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <div>
            <h3 className="text-lg font-semibold">Varredura de orfaos</h3>
            <p className="text-sm text-muted">
              Conta linhas com player_id/account_id/nome apontando para registros inexistentes.
            </p>
          </div>
          <button
            type="button"
            onClick={onOrphanScan}
            disabled={orphanBusy}
            className="rounded-md bg-brand px-4 py-2 text-sm text-background disabled:opacity-50"
          >
            {orphanBusy ? labels.loading : "Rodar varredura"}
          </button>
        </div>
        {orphanErr && <p className="text-sm text-red-400">{orphanErr}</p>}
        {orphanMeta && (
          <p className="text-sm">
            Total: <strong>{orphanMeta.orphanTotal}</strong> em{" "}
            <strong>{orphanMeta.orphanGroups}</strong> grupos
            {orphanMeta.note ? ` - ${orphanMeta.note}` : ""}
          </p>
        )}
        {orphans && orphans.length === 0 && (
          <p className="text-sm text-muted">Nenhum orfao encontrado nas checagens ativas.</p>
        )}
        {orphanMsg && <p className="text-sm text-brand">{orphanMsg}</p>}
        {orphans && orphans.length > 0 && (
          <div className="overflow-auto rounded-md border border-border">
            <table className="min-w-full text-left text-sm">
              <thead className="bg-background text-muted">
                <tr>
                  <th className="px-3 py-2 font-medium">Tabela</th>
                  <th className="px-3 py-2 font-medium">Tipo</th>
                  <th className="px-3 py-2 font-medium">Qtd</th>
                  {/* BEGIN CHANGE: item 6 - coluna de acao */}
                  <th className="px-3 py-2 font-medium">Acao</th>
                  {/* END CHANGE */}
                </tr>
              </thead>
              <tbody>
                {orphans.map((row) => (
                  <tr key={`${row.table}-${row.kind}`} className="border-t border-border">
                    <td className="px-3 py-2 font-mono text-xs">{row.table}</td>
                    <td className="px-3 py-2">{row.kind}</td>
                    <td className="px-3 py-2">{row.count}</td>
                    {/* BEGIN CHANGE: item 6 - botao tratar/excluir orfaos */}
                    <td className="px-3 py-2">
                      <button
                        type="button"
                        disabled={orphanBusy || row.count === 0}
                        className="rounded border border-red-500/50 px-2 py-1 text-xs text-red-300 hover:border-red-400 disabled:opacity-50"
                        onClick={() => setPendingOrphan(row)}
                      >
                        Tratar/Excluir
                      </button>
                    </td>
                    {/* END CHANGE */}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* BEGIN CHANGE: item 6 - confirmacao para exclusao de orfaos */}
      <AdminConfirmModal
        open={!!pendingOrphan}
        title={
          pendingOrphan
            ? `Tratar orfaos: ${pendingOrphan.table} (${pendingOrphan.kind}) - ${pendingOrphan.count}`
            : ""
        }
        hint="Remove as linhas orfas deste grupo (houses/marriage sao corrigidos; player sem conta e removido em cascata). Inclui historico de shop e pagamentos orfaos. Acao irreversivel - digite DELETE e sua senha de admin."
        requirePassword
        requireDeleteWord
        confirmLabel="Confirmar"
        cancelLabel="Cancelar"
        passwordLabel="Sua senha de admin"
        onCancel={() => setPendingOrphan(null)}
        onConfirm={({ adminPassword, confirm }) => {
          const row = pendingOrphan;
          setPendingOrphan(null);
          if (row) runOrphanDelete(row, adminPassword || "", confirm || "");
        }}
      />
      {/* END CHANGE */}
    </div>
  );
}
// END CHANGE
