// BEGIN CHANGE: secao economia (doacoes + fila shop)
"use client";

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

type QueueRow = {
  id: number;
  name: string;
  type: string;
  action: string;
  param1: string;
  param2: string;
  deleteIt: number;
};

type Undelivered = {
  toName: string;
  toAccount: number;
  item: string;
  price: number;
  start: number;
  source: string;
  catalog?: string;
};

// BEGIN CHANGE: shop analytics essentials
type ShopStats = {
  queueCount: number;
  waitingHistory: number;
  spentDonate7d: number;
  spentDonate30d: number;
  spentGuild30d: number;
  avgWaitSec: number;
  topOffers: { offerId: number; name: string; count: number; spent: number }[];
};
// END CHANGE

// BEGIN CHANGE: admin shop purchase history
type ShopPurchaseRow = {
  kind: string;
  id: number;
  catalog: string;
  toName: string;
  toAccount: number;
  toPlayerId: number;
  fromNick: string;
  fromAccount: number;
  buyerIp: string;
  price: number;
  quantity: number;
  offerId: number;
  itemName: string;
  days: number;
  state: string;
  started: number;
  realized: number;
  serialItem: string;
  payload: Record<string, unknown> | null;
};
// END CHANGE

export function AdminEconomy({
  token,
  onGoAccount,
  labels,
}: {
  token: string;
  onGoAccount: (account: string) => void;
  labels: {
    loading: string;
    failed: string;
    refresh: string;
    donations: string;
    filterAccount: string;
    filterProvider: string;
    onlyUnprocessed: string;
    shopQueue: string;
    undelivered: string;
    allProviders: string;
  };
}) {
  const [donations, setDonations] = useState<{
    mercadopago: DonationRow[];
    paypal: DonationRow[];
    pagseguro: DonationRow[];
  } | null>(null);
  const [queue, setQueue] = useState<QueueRow[]>([]);
  const [undelivered, setUndelivered] = useState<Undelivered[]>([]);
  // BEGIN CHANGE: shop analytics essentials
  const [shopStats, setShopStats] = useState<ShopStats | null>(null);
  // END CHANGE
  // BEGIN CHANGE: admin shop purchase history
  const [shopPurchases, setShopPurchases] = useState<ShopPurchaseRow[]>([]);
  const [shopAccount, setShopAccount] = useState("");
  const [shopDays, setShopDays] = useState(30);
  const [shopCatalog, setShopCatalog] = useState<"all" | "donate" | "guild">("all");
  const [shopState, setShopState] = useState<"all" | "wait" | "realized">("all");
  const [expandedPayload, setExpandedPayload] = useState<string | null>(null);
  // END CHANGE
  const [accountFilter, setAccountFilter] = useState("");
  const [provider, setProvider] = useState<"all" | "mercadopago" | "paypal" | "pagseguro">("all");
  const [onlyUnprocessed, setOnlyUnprocessed] = useState(false);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  async function loadShopHistory() {
    const qs = new URLSearchParams({
      tool: "shop_history",
      days: String(shopDays),
      catalog: shopCatalog,
      state: shopState,
    });
    if (shopAccount.trim()) qs.set("account", shopAccount.trim());
    const r = await fetch(apiUrl(`admin-panel.php?${qs.toString()}`), {
      headers: { Authorization: `Bearer ${token}` },
    });
    const json = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(json.error || "shop_history");
    setShopPurchases(json.data?.rows || []);
  }

  async function load() {
    setBusy(true);
    setErr("");
    try {
      const qs = accountFilter.trim()
        ? `&account=${encodeURIComponent(accountFilter.trim())}`
        : "";
      const [dRes, qRes] = await Promise.all([
        fetch(apiUrl(`admin-panel.php?tool=donations${qs}`), {
          headers: { Authorization: `Bearer ${token}` },
        }),
        fetch(apiUrl("admin-panel.php?tool=shop_queue"), {
          headers: { Authorization: `Bearer ${token}` },
        }),
      ]);
      const dJson = await dRes.json().catch(() => ({}));
      const qJson = await qRes.json().catch(() => ({}));
      if (!dRes.ok) throw new Error(dJson.error || "donations");
      if (!qRes.ok) throw new Error(qJson.error || "queue");
      setDonations(dJson.data);
      setQueue(qJson.data?.queue || []);
      setUndelivered(qJson.data?.undelivered || []);
      // BEGIN CHANGE: shop analytics essentials
      setShopStats(qJson.data?.stats || null);
      // END CHANGE
      // BEGIN CHANGE: admin shop purchase history
      await loadShopHistory();
      // END CHANGE
    } catch {
      setErr(labels.failed);
    } finally {
      setBusy(false);
    }
  }

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

  const rows = useMemo(() => {
    if (!donations) return [];
    let list: DonationRow[] = [];
    if (provider === "all" || provider === "mercadopago") list = list.concat(donations.mercadopago || []);
    if (provider === "all" || provider === "paypal") list = list.concat(donations.paypal || []);
    if (provider === "all" || provider === "pagseguro") list = list.concat(donations.pagseguro || []);
    if (onlyUnprocessed) list = list.filter((d) => d.processed === false);
    return list;
  }, [donations, provider, onlyUnprocessed]);

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-end gap-3">
        <label className="text-sm">
          <span className="text-muted">{labels.filterAccount}</span>
          <input
            className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
            value={accountFilter}
            onChange={(e) => setAccountFilter(e.target.value)}
          />
        </label>
        <label className="text-sm">
          <span className="text-muted">{labels.filterProvider}</span>
          <select
            className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
            value={provider}
            onChange={(e) => setProvider(e.target.value as typeof provider)}
          >
            <option value="all">{labels.allProviders}</option>
            <option value="mercadopago">MercadoPago</option>
            <option value="paypal">PayPal</option>
            <option value="pagseguro">PagSeguro (legado)</option>
          </select>
        </label>
        <label className="inline-flex items-center gap-2 text-sm">
          <input
            type="checkbox"
            checked={onlyUnprocessed}
            onChange={(e) => setOnlyUnprocessed(e.target.checked)}
          />
          {labels.onlyUnprocessed}
        </label>
        <button
          type="button"
          disabled={busy}
          onClick={load}
          className="rounded-md border border-border px-3 py-2 text-sm disabled:opacity-50"
        >
          {labels.refresh}
        </button>
      </div>
      {err && <p className="text-sm text-red-400">{err}</p>}

      {/* BEGIN CHANGE: shop analytics essentials */}
      {shopStats && (
        <CollapsiblePanel id="admin-econ-analytics" title="Shop analytics" titleClassName="text-lg font-semibold">
          <div className="grid gap-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
            <p>
              Fila agora: <span className="font-medium">{shopStats.queueCount}</span>
            </p>
            <p>
              Historico aguardando:{" "}
              <span className="font-medium">{shopStats.waitingHistory}</span>
            </p>
            <p>
              Espera media (30d):{" "}
              <span className="font-medium">
                {shopStats.avgWaitSec > 0 ? `${shopStats.avgWaitSec}s` : "-"}
              </span>
            </p>
            <p>
              PP gasto 7d:{" "}
              <span className="font-medium text-brand">{shopStats.spentDonate7d}</span>
            </p>
            <p>
              PP gasto 30d:{" "}
              <span className="font-medium text-brand">{shopStats.spentDonate30d}</span>
            </p>
            <p>
              GP gasto 30d:{" "}
              <span className="font-medium text-brand">{shopStats.spentGuild30d}</span>
            </p>
          </div>
          {(shopStats.topOffers?.length ?? 0) > 0 && (
            <div className="mt-3">
              <p className="text-xs text-muted">Top ofertas (30d)</p>
              <ul className="mt-1 max-h-40 space-y-1 overflow-auto text-sm text-muted">
                {shopStats.topOffers.map((o) => (
                  <li key={`${o.offerId}-${o.name}`}>
                    #{o.offerId} {o.name || "-"} - {o.count}x - {o.spent} pts
                  </li>
                ))}
              </ul>
            </div>
          )}
        </CollapsiblePanel>
      )}
      {/* END CHANGE */}

      <CollapsiblePanel id="admin-econ-donations" title={labels.donations} titleClassName="text-lg font-semibold">
        <div className="mt-3 max-h-80 overflow-auto">
          <table className="w-full text-left text-sm">
            <thead className="sticky top-0 bg-panel text-muted">
              <tr>
                <th className="py-1 pr-2">Prov</th>
                <th className="py-1 pr-2">Acc</th>
                <th className="py-1 pr-2">Valor</th>
                <th className="py-1 pr-2">Pts</th>
                <th className="py-1 pr-2">Status</th>
                <th className="py-1">Quando</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((d) => (
                <tr key={d.provider + d.id} className="border-t border-border/40">
                  <td className="py-1 pr-2">{d.provider}</td>
                  <td className="py-1 pr-2">
                    <button
                      type="button"
                      className="text-brand hover:underline"
                      onClick={() => onGoAccount(d.account)}
                    >
                      {d.account}
                    </button>
                  </td>
                  <td className="py-1 pr-2">
                    {d.amount}
                    {d.currency ? ` ${d.currency}` : ""}
                  </td>
                  <td className="py-1 pr-2">{d.points ?? "-"}</td>
                  <td className="py-1 pr-2">
                    {d.status}
                    {d.processed === false ? (
                      <span className="ml-1 text-amber-300">unprocessed</span>
                    ) : null}
                  </td>
                  <td className="py-1">{d.when}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </CollapsiblePanel>

      {/* BEGIN CHANGE: admin shop purchase history */}
      <CollapsiblePanel
        id="admin-econ-shop-history"
        title="Historico de compras (shop)"
        titleClassName="text-lg font-semibold"
      >
        <p className="text-xs text-muted">
          Filtro por conta/char, periodo, catalogo e estado. Snapshot (payload) so em compras novas.
        </p>
        <div className="mt-3 flex flex-wrap items-end gap-3">
          <label className="text-sm">
            <span className="text-muted">Conta / char</span>
            <input
              className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
              value={shopAccount}
              onChange={(e) => setShopAccount(e.target.value)}
              placeholder="alana / Alana Bunduda"
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">Dias</span>
            <select
              className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
              value={shopDays}
              onChange={(e) => setShopDays(Number(e.target.value) || 30)}
            >
              <option value={7}>7</option>
              <option value={30}>30</option>
              <option value={90}>90</option>
              <option value={365}>365</option>
            </select>
          </label>
          <label className="text-sm">
            <span className="text-muted">Catalogo</span>
            <select
              className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
              value={shopCatalog}
              onChange={(e) => setShopCatalog(e.target.value as typeof shopCatalog)}
            >
              <option value="all">Todos</option>
              <option value="donate">Donate</option>
              <option value="guild">Guild</option>
            </select>
          </label>
          <label className="text-sm">
            <span className="text-muted">Estado</span>
            <select
              className="mt-1 block rounded-md border border-border bg-background px-3 py-2 text-sm"
              value={shopState}
              onChange={(e) => setShopState(e.target.value as typeof shopState)}
            >
              <option value="all">Todos</option>
              <option value="wait">Aguardando</option>
              <option value="realized">Entregue</option>
            </select>
          </label>
          <button
            type="button"
            disabled={busy}
            onClick={() => {
              void (async () => {
                setBusy(true);
                setErr("");
                try {
                  await loadShopHistory();
                } catch {
                  setErr(labels.failed);
                } finally {
                  setBusy(false);
                }
              })();
            }}
            className="rounded-md border border-border px-3 py-2 text-sm disabled:opacity-50"
          >
            Filtrar
          </button>
        </div>
        <div className="mt-3 max-h-96 overflow-auto">
          <table className="w-full min-w-[880px] text-left text-xs">
            <thead className="sticky top-0 bg-panel text-muted">
              <tr>
                <th className="py-1 pr-2">Quando</th>
                <th className="py-1 pr-2">De</th>
                <th className="py-1 pr-2">Para</th>
                <th className="py-1 pr-2">O que</th>
                <th className="py-1 pr-2">Preco</th>
                <th className="py-1 pr-2">Estado</th>
                <th className="py-1 pr-2">IP</th>
                <th className="py-1">Payload</th>
              </tr>
            </thead>
            <tbody>
              {shopPurchases.map((h) => {
                const key = `${h.kind}-${h.id}`;
                const what =
                  h.kind === "pacc"
                    ? `${h.days}d premium`
                    : h.itemName || (h.offerId > 0 ? `#${h.offerId}` : "-");
                return (
                  <tr key={key} className="border-t border-border/40 align-top">
                    <td className="py-1 pr-2 whitespace-nowrap">{fmtTs(h.started)}</td>
                    <td className="py-1 pr-2">
                      <button
                        type="button"
                        className="text-brand hover:underline"
                        onClick={() => onGoAccount(h.fromNick || String(h.fromAccount))}
                      >
                        {h.fromNick || h.fromAccount || "-"}
                      </button>
                    </td>
                    <td className="py-1 pr-2">
                      {h.toName}
                      {h.toPlayerId > 0 ? (
                        <span className="block text-[10px] text-muted">pid {h.toPlayerId}</span>
                      ) : null}
                    </td>
                    <td className="py-1 pr-2">
                      {what}
                      {h.quantity > 1 ? ` x${h.quantity}` : ""}
                      <span className="ml-1 text-muted">
                        ({h.catalog === "guild" ? "GP" : "PP"})
                      </span>
                    </td>
                    <td className="py-1 pr-2 text-brand">{h.price}</td>
                    <td className="py-1 pr-2">
                      {h.state === "wait" ? "wait" : "ok"}
                    </td>
                    <td className="py-1 pr-2 font-mono text-[10px]">{h.buyerIp || "-"}</td>
                    <td className="py-1">
                      {h.payload ? (
                        <button
                          type="button"
                          className="text-brand hover:underline"
                          onClick={() =>
                            setExpandedPayload((cur) => (cur === key ? null : key))
                          }
                        >
                          {expandedPayload === key ? "ocultar" : "ver"}
                        </button>
                      ) : (
                        <span className="text-muted">-</span>
                      )}
                      {expandedPayload === key && h.payload ? (
                        <pre className="mt-1 max-w-md overflow-auto rounded border border-border/50 bg-background p-2 text-[10px] text-muted">
                          {JSON.stringify(h.payload, null, 2)}
                        </pre>
                      ) : null}
                    </td>
                  </tr>
                );
              })}
              {shopPurchases.length === 0 ? (
                <tr>
                  <td colSpan={8} className="py-3 text-muted">
                    Nenhuma compra no filtro.
                  </td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </CollapsiblePanel>
      {/* END CHANGE */}

      <CollapsiblePanel
        id="admin-econ-queue"
        title={`${labels.shopQueue} (${queue.length})`}
        titleClassName="text-lg font-semibold"
        defaultOpen={false}
      >
        <div className="max-h-64 overflow-auto">
          <table className="w-full text-left text-xs">
            <thead className="text-muted">
              <tr>
                <th className="py-1 pr-2">ID</th>
                <th className="py-1 pr-2">Player</th>
                <th className="py-1 pr-2">Action</th>
                <th className="py-1 pr-2">P1/P2</th>
              </tr>
            </thead>
            <tbody>
              {queue.map((q) => (
                <tr key={q.id} className="border-t border-border/40">
                  <td className="py-1 pr-2">{q.id}</td>
                  <td className="py-1 pr-2">{q.name}</td>
                  <td className="py-1 pr-2">
                    {q.type}/{q.action}
                  </td>
                  <td className="py-1 pr-2">
                    {q.param1}/{q.param2}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </CollapsiblePanel>

      <CollapsiblePanel
        id="admin-econ-undelivered"
        title={`${labels.undelivered} (${undelivered.length})`}
        titleClassName="text-lg font-semibold"
        defaultOpen={false}
      >
        <ul className="max-h-48 space-y-1 overflow-auto text-sm text-muted">
          {undelivered.map((u, i) => (
            <li key={i}>
              {u.toName} - {u.source || "shop"} - {u.item || "COMBO"} - {u.price}{" "}
              {u.catalog === "guild" ? "GP" : "PP"} - {fmtTs(u.start)}
            </li>
          ))}
        </ul>
      </CollapsiblePanel>
    </div>
  );
}
// END CHANGE
