// BEGIN CHANGE: painel admin em secoes (dashboard, contas, economia, shop, cms, moderacao, serial, tools, audit)
"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useI18n } from "@/i18n/LanguageProvider";
import { useAuth } from "@/auth/AuthProvider";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { apiUrl } from "@/lib/api";
import { AdminCmsPanel } from "@/components/AdminCmsPanel";
import { AdminShopPanel } from "@/components/AdminShopPanel";
import { AdminDashboard } from "@/components/admin/AdminDashboard";
import { AdminInspector } from "@/components/admin/AdminInspector";
import { AdminEconomy } from "@/components/admin/AdminEconomy";
import { AdminModeration } from "@/components/admin/AdminModeration";
import { AdminSerial } from "@/components/admin/AdminSerial";
import { AdminTools } from "@/components/admin/AdminTools";
import { AdminAuditPanel } from "@/components/admin/AdminAuditPanel";
import { AdminWipePlayers } from "@/components/admin/AdminWipePlayers";
// BEGIN CHANGE: novas secoes - console SQL (item 8) e notificacoes (item 10)
import { AdminSql } from "@/components/admin/AdminSql";
import { AdminNotify } from "@/components/admin/AdminNotify";
// END CHANGE
// BEGIN CHANGE: Jackpot admin log
import { AdminJackpot } from "@/components/admin/AdminJackpot";
// END CHANGE
// BEGIN CHANGE: serial anti-dupe admin log
import { AdminSerialAntidupe } from "@/components/admin/AdminSerialAntidupe";
// END CHANGE
import {
  ACCESS_ADMIN,
  ACCESS_SUBADMIN,
  accessLabel,
  canCms,
  canCritical,
  canEconomy,
} from "@/components/admin/acl";
import type { AdminSection } from "@/components/admin/types";

export default function AdminPage() {
  const { t } = useI18n();
  const { ready, token, account } = useAuth();
  const access = account?.pageAccess ?? 0;
  const canUsePanel = !!(account && (account.canAccessAdminPanel ?? access > 2));

  const [section, setSection] = useState<AdminSection>("dashboard");
  const [inspectQuery, setInspectQuery] = useState<string | undefined>();
  const [inspectMode, setInspectMode] = useState<"player" | "account" | "accountId" | undefined>();
  const [inspectKey, setInspectKey] = useState(0);
  const [flash, setFlash] = useState("");
  const [flashErr, setFlashErr] = useState("");

  useEffect(() => {
    if (!ready) return;
    if (!token) window.location.href = "/login";
  }, [ready, token]);

  const nav = useMemo(() => {
    const items: { id: AdminSection; label: string; show: boolean }[] = [
      { id: "dashboard", label: "Dashboard", show: canCms(access) },
      { id: "accounts", label: "Contas / Players", show: canCms(access) },
      { id: "economy", label: "Economia", show: canEconomy(access) },
      { id: "shop", label: "Catalogo Shop", show: canEconomy(access) },
      { id: "cms", label: "CMS", show: canCms(access) },
      // BEGIN CHANGE: item 10 - notificacoes globais (staff)
      { id: "notify", label: "Notificacoes", show: canCms(access) },
      // END CHANGE
      { id: "moderation", label: "Moderacao", show: canCms(access) },
      { id: "serial", label: "Serial Staff", show: canCms(access) },
      { id: "tools", label: "Ferramentas", show: canCms(access) },
      // BEGIN CHANGE: Jackpot admin log
      { id: "jackpot", label: "Jackpot Log", show: canCms(access) },
      // END CHANGE
      // BEGIN CHANGE: serial anti-dupe admin log
      { id: "serial_antidupe", label: "Anti-Dupe Log", show: canCms(access) },
      // END CHANGE
      { id: "wipe", label: "Wipe / Reset", show: canCritical(access) },
      // BEGIN CHANGE: item 8 - console SQL (admin)
      { id: "sql", label: "Console SQL", show: canCritical(access) },
      // END CHANGE
      { id: "audit", label: "Audit Log", show: canCritical(access) },
    ];
    return items.filter((i) => i.show);
  }, [access]);

  function goAccounts(opts?: { account?: string; player?: string; accountId?: number }) {
    setSection("accounts");
    setInspectKey((k) => k + 1);
    if (opts?.accountId) {
      setInspectMode("accountId");
      setInspectQuery(String(opts.accountId));
    } else if (opts?.account) {
      setInspectMode("account");
      setInspectQuery(opts.account);
    } else if (opts?.player) {
      setInspectMode("player");
      setInspectQuery(opts.player);
    } else {
      setInspectMode(undefined);
      setInspectQuery(undefined);
    }
  }

  async function postAction(body: Record<string, unknown>) {
    if (!token) return;
    setFlash("");
    setFlashErr("");
    const r = await fetch(apiUrl("admin-panel.php"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(body),
    });
    const json = await r.json().catch(() => ({}));
    if (!r.ok) {
      setFlashErr(json.error || t.admin.actionFailed);
      return;
    }
    setFlash(json.note || t.admin.actionOk);
  }

  const inspectorLabels: Record<string, string> = {
    accountSection: t.admin.accountSection,
    byPlayer: t.admin.byPlayer,
    byAccount: t.admin.byAccount,
    playerPlaceholder: t.admin.playerPlaceholder,
    accountPlaceholder: t.admin.accountPlaceholder,
    search: t.admin.search,
    loading: t.common.loading,
    failed: t.admin.actionFailed,
    notFound: t.admin.notFound,
    accountName: t.admin.accountName,
    passwordHash: t.admin.passwordHash,
    recoveryKey: t.admin.recoveryKey,
    noRecoveryKey: t.admin.noRecoveryKey,
    pageAccess: t.admin.pageAccess,
    premiumPoints: t.admin.premiumPoints,
    backupPoints: t.admin.backupPoints,
    backupPointsHint: t.admin.backupPointsHint,
    guildPoints: t.admin.guildPoints,
    blocked: t.admin.blocked,
    actionsSection: t.admin.actionsSection,
    setPoints: t.admin.setPoints,
    setAccess: t.admin.setAccess,
    setEmail: t.admin.setEmail,
    setPassword: t.admin.setPassword,
    setPasswordHint: t.admin.setPasswordHint,
    setPremDays: t.admin.setPremDays,
    renameAccount: t.admin.renameAccount,
    blockAccount: t.admin.blockAccount,
    block: t.admin.block,
    unblock: t.admin.unblock,
    regenKey: t.admin.regenKey,
    newRecoveryKey: t.admin.newRecoveryKey,
    playersSection: t.admin.playersSection,
    shopSection: t.admin.shopSection,
    save: t.admin.save,
    apply: t.admin.apply,
    actionOk: t.admin.actionOk,
    actionFailed: t.admin.actionFailed,
    empty: t.common.empty,
    showSecrets: "Mostrar secrets",
    hideSecrets: "Ocultar secrets",
    noEconomy: "Requer page_access >= 5 (Subadmin).",
    noCritical: "Requer page_access >= 6 (Admin).",
    openCharacter: "Abrir personagem",
    openSerial: "Item Serial",
    playerOnline: "Player ONLINE - acoes offline bloqueadas",
    dangerZone: "Zona perigosa",
    deletePlayer: "Excluir personagem",
    deleteAccount: "Excluir account",
    donationsAccount: "Doacoes desta conta",
    confirmTitle: "Confirmar acao",
    confirmHint: "Digite sua senha de admin para continuar.",
    confirmBtn: "Confirmar",
    cancel: "Cancelar",
    adminPassword: "Sua senha de admin",
    adminPasswordRequired: "Senha de admin obrigatoria ou incorreta.",
  };

  return (
    <div className="flex min-h-screen flex-col">
      <Navbar />
      <main className="mx-auto w-full max-w-6xl flex-1 px-6 py-14">
        <Link href="/account" className="text-sm text-muted hover:text-brand">
          &larr; {t.auth.myAccount}
        </Link>
        <div className="mt-4 flex flex-wrap items-end justify-between gap-3">
          <div>
            <h1 className="text-3xl font-semibold tracking-tight">{t.admin.title}</h1>
            <p className="mt-2 max-w-2xl text-sm text-muted">{t.admin.subtitle}</p>
          </div>
          {canUsePanel && (
            <span className="rounded-full border border-border px-3 py-1 text-xs text-muted">
              {accessLabel(access)} (page_access {access})
            </span>
          )}
        </div>

        {!ready && <p className="mt-8 text-muted">{t.common.loading}</p>}

        {ready && !canUsePanel && (
          <p className="mt-8 rounded-lg border border-border bg-panel px-4 py-3 text-sm text-muted">
            {t.admin.denied}
          </p>
        )}

        {ready && canUsePanel && token && (
          <div className="mt-8 grid gap-6 lg:grid-cols-[220px_1fr]">
            <nav className="h-fit space-y-1 rounded-xl border border-border bg-panel p-2">
              {nav.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  onClick={() => {
                    setSection(item.id);
                    setFlash("");
                    setFlashErr("");
                  }}
                  className={`block w-full rounded-lg px-3 py-2 text-left text-sm ${
                    section === item.id
                      ? "bg-brand text-background"
                      : "text-muted hover:bg-brand/10 hover:text-foreground"
                  }`}
                >
                  {item.label}
                </button>
              ))}
              <div className="border-t border-border/50 pt-2 text-xs text-muted px-3 py-1">
                CMS {">"}2 - Econ {">"}={ACCESS_SUBADMIN} - Crit {">"}={ACCESS_ADMIN}
              </div>
            </nav>

            <div>
              {flash && <p className="mb-4 text-sm text-brand">{flash}</p>}
              {flashErr && <p className="mb-4 text-sm text-red-400">{flashErr}</p>}

              {section === "dashboard" && (
                <AdminDashboard
                  token={token}
                  canUnban={canEconomy(access)}
                  onGo={(s, opts) => {
                    if (s === "accounts") goAccounts(opts);
                    else setSection(s);
                  }}
                  labels={{
                    loading: t.common.loading,
                    failed: t.admin.actionFailed,
                    refresh: "Atualizar",
                    online: "Online",
                    accounts: "Contas",
                    players: "Players",
                    bans: "Bans ativos",
                    shopQueue: "Fila shop",
                    undelivered: "Shop nao entregue",
                    unprocessedDonations: "Doacoes unprocessed",
                    helpdesk: "Helpdesk aguardando",
                    recentDonations: "Doacoes recentes",
                    recentBans: "Bans recentes",
                    openSupport: "Abrir Support",
                    openEconomy: "Ir para Economia",
                    openModeration: "Ir para Moderacao",
                  }}
                />
              )}

              {section === "accounts" && (
                <AdminInspector
                  key={inspectKey}
                  token={token}
                  access={access}
                  initialQuery={inspectQuery}
                  initialMode={inspectMode}
                  labels={inspectorLabels}
                />
              )}

              {section === "economy" && (
                <AdminEconomy
                  token={token}
                  onGoAccount={(accountName) => goAccounts({ account: accountName })}
                  labels={{
                    loading: t.common.loading,
                    failed: t.admin.actionFailed,
                    refresh: "Atualizar",
                    donations: "Doacoes",
                    filterAccount: "Filtrar conta",
                    filterProvider: "Provider",
                    onlyUnprocessed: "So unprocessed",
                    shopQueue: "Fila z_ots_comunication",
                    undelivered: "Compras nao entregues",
                    allProviders: "Todos",
                  }}
                />
              )}

              {section === "shop" && (
                <AdminShopPanel
                  token={token}
                  labels={{
                    shopOffersSection: t.admin.shopOffersSection,
                    shopOffersHint: t.admin.shopOffersHint,
                    shopCatalogDonate: t.admin.shopCatalogDonate,
                    shopCatalogGuild: t.admin.shopCatalogGuild,
                    shopOfferNew: t.admin.shopOfferNew,
                    shopOfferEdit: t.admin.shopOfferEdit,
                    shopOfferName: t.admin.shopOfferName,
                    shopOfferDesc: t.admin.shopOfferDesc,
                    shopOfferPoints: t.admin.shopOfferPoints,
                    shopOfferType: t.admin.shopOfferType,
                    shopOfferGroup: t.admin.shopOfferGroup,
                    shopOfferSlots: t.admin.shopOfferSlots,
                    shopOfferSlotItem: t.admin.shopOfferSlotItem,
                    shopOfferSlotCount: t.admin.shopOfferSlotCount,
                    shopOfferSave: t.admin.shopOfferSave,
                    shopOfferCancel: t.admin.shopOfferCancel,
                    shopOfferDelete: t.admin.shopOfferDelete,
                    shopOfferConfirmDelete: t.admin.shopOfferConfirmDelete,
                    shopOfferAllowQty: t.admin.shopOfferAllowQty,
                    shopOfferMaxQty: t.admin.shopOfferMaxQty,
                    shopOfferQtyHint: t.admin.shopOfferQtyHint,
                    shopOfferActive: t.admin.shopOfferActive,
                    shopOfferInactive: t.admin.shopOfferInactive,
                    shopBundleGroups: t.admin.shopBundleGroups,
                    shopBundleGroupLabel: t.admin.shopBundleGroupLabel,
                    shopBundleMin: t.admin.shopBundleMin,
                    shopBundleMax: t.admin.shopBundleMax,
                    shopBundleAddGroup: t.admin.shopBundleAddGroup,
                    shopBundleRemoveGroup: t.admin.shopBundleRemoveGroup,
                    shopBundleOptionLabel: t.admin.shopBundleOptionLabel,
                    shopBundleAddOption: t.admin.shopBundleAddOption,
                    shopBundleRemoveOption: t.admin.shopBundleRemoveOption,
                    shopBundleAddItem: t.admin.shopBundleAddItem,
                    shopBundleRemoveItem: t.admin.shopBundleRemoveItem,
                    shopBundleHint: t.admin.shopBundleHint,
                    shopManualTitle: t.admin.shopManualTitle,
                    shopManualSections: t.admin.shopManualSections,
                    save: t.admin.save,
                    actionOk: t.admin.actionOk,
                    actionFailed: t.admin.actionFailed,
                    delete: t.admin.cmsDelete,
                    loading: t.common.loading,
                  }}
                />
              )}

              {section === "cms" && (
                <AdminCmsPanel
                  token={token}
                  labels={{
                    homeSection: t.admin.cmsHome,
                    homeHint: t.admin.cmsHomeHint,
                    contactsSection: t.admin.cmsContacts,
                    contactsHint: t.admin.cmsContactsHint,
                    contactsTelegram: t.admin.cmsContactsTelegram,
                    contactsDiscord: t.admin.cmsContactsDiscord,
                    contactsEmail: t.admin.cmsContactsEmail,
                    newsSection: t.admin.cmsNews,
                    changelogSection: t.admin.cmsChangelog,
                    pollsSection: t.admin.cmsPolls,
                    save: t.admin.save,
                    apply: t.admin.apply,
                    actionOk: t.admin.actionOk,
                    actionFailed: t.admin.actionFailed,
                    badge: t.admin.cmsBadge,
                    titlePre: t.admin.cmsTitlePre,
                    titleBrand: t.admin.cmsTitleBrand,
                    subtitle: t.admin.cmsSubtitle,
                    newsText: t.admin.cmsNewsText,
                    newsIcon: t.admin.cmsNewsIcon,
                    addNews: t.admin.cmsAddNews,
                    hide: t.admin.cmsHide,
                    show: t.admin.cmsShow,
                    changelogType: t.admin.cmsClType,
                    changelogPlace: t.admin.cmsClPlace,
                    changelogDesc: t.admin.cmsClDesc,
                    addChangelog: t.admin.cmsAddChangelog,
                    delete: t.admin.cmsDelete,
                    pollQuestion: t.admin.cmsPollQuestion,
                    pollDays: t.admin.cmsPollDays,
                    pollAnswers: t.admin.cmsPollAnswers,
                    pollAnswersHint: t.admin.cmsPollAnswersHint,
                    pollAddOption: t.admin.cmsPollAddOption,
                    pollRemoveOption: t.admin.cmsPollRemoveOption,
                    createPoll: t.admin.cmsCreatePoll,
                    active: t.admin.cmsActive,
                    closed: t.admin.cmsClosed,
                    loading: t.common.loading,
                  }}
                />
              )}

              {section === "moderation" && (
                <AdminModeration
                  token={token}
                  access={access}
                  postAction={postAction}
                  labels={{
                    loading: t.common.loading,
                    failed: t.admin.actionFailed,
                    refresh: "Atualizar",
                    bans: "Bans ativos",
                    unban: "Unban",
                    monsterNames: "Players com nome de monstro",
                    deleteAll: "Excluir todos (DELETE)",
                    banCommands: "Comandos de ban in-game",
                    massEmail: "E-mail em massa",
                    subject: "Assunto",
                    body: "Mensagem",
                    send: "Enviar",
                    openSupport: "Helpdesk / Support",
                    noPermission: "Sem permissao",
                    confirmTitle: "Confirmar acao",
                    confirmHint: "Confirme com sua senha de admin.",
                    confirmBtn: "Confirmar",
                    cancel: "Cancelar",
                    adminPassword: "Sua senha de admin",
                  }}
                />
              )}

              {section === "serial" && (
                <AdminSerial
                  token={token}
                  onGoAccountId={(id) => goAccounts({ accountId: id })}
                  onGoPlayer={(name) => goAccounts({ player: name })}
                  labels={{
                    title: "Serial Staff",
                    hint: "Busca de serial sem gate de Premium (staff).",
                    findBtn: "Buscar",
                    failed: t.admin.actionFailed,
                    notFound: "Serial nao encontrado.",
                    openAccount: "Abrir conta",
                  }}
                />
              )}

              {section === "tools" && (
                <AdminTools
                  token={token}
                  labels={{
                    title: "Ferramentas",
                    houseHint:
                      "House items, rastreio pos-delete (shop/historicos) e varredura de orfaos no schema.",
                    playerName: "Nome do personagem",
                    search: t.admin.search,
                    failed: t.admin.actionFailed,
                    loading: t.common.loading,
                  }}
                />
              )}

              {/* BEGIN CHANGE: Jackpot admin log */}
              {section === "jackpot" && <AdminJackpot token={token} />}
              {/* END CHANGE */}
              {/* BEGIN CHANGE: serial anti-dupe admin log */}
              {section === "serial_antidupe" && <AdminSerialAntidupe token={token} />}
              {/* END CHANGE */}

              {section === "wipe" && (
                <AdminWipePlayers token={token} canUse={canCritical(access)} />
              )}

              {/* BEGIN CHANGE: item 10 - notificacoes globais */}
              {section === "notify" && <AdminNotify token={token} />}
              {/* END CHANGE */}

              {/* BEGIN CHANGE: item 8 - console SQL */}
              {section === "sql" && <AdminSql token={token} />}
              {/* END CHANGE */}

              {section === "audit" && (
                <AdminAuditPanel
                  token={token}
                  labels={{
                    title: "Audit Log",
                    loading: t.common.loading,
                    failed: t.admin.actionFailed,
                    refresh: "Atualizar",
                    denied: "Acesso restrito (page_access >= 6).",
                  }}
                />
              )}
            </div>
          </div>
        )}
      </main>
      <Footer />
    </div>
  );
}
// END CHANGE
