'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'

type Tool = { href: string; icon: string; label: string; desc: string; labelClass?: string }

/** Replica los paneles plegables «OPCIONES DE CUENTA / OPCIONES DE PERSONAJE»
 *  del my-account de Django (acordeón por click), con las herramientas ya
 *  implementadas en Next. */
export function AccountTools({ isAdmin, storeHref }: { isAdmin: boolean; storeHref: string }) {
  const t = useTranslations('Account')

  const accountTools: Tool[] = [
    { href: '/change-password', icon: 'password-icon', label: t('svcChangePassword'), desc: t('svcChangePasswordDesc') },
    { href: '/security-2falogin', icon: 'email-icon', label: t('svc2FA'), desc: t('svc2FADesc'), labelClass: 'purple-info' },
    { href: '/transfer-d-points', icon: 'transfer-dp-icon', label: t('svcTransferDP'), desc: t('svcTransferDPDesc') },
    { href: '/trade-points', icon: 'trade-pd-icon', label: t('svcTradePD'), desc: t('svcTradePDDesc') },
    { href: '/promo-code', icon: 'promo-icon', label: t('svcPromo'), desc: t('svcPromoDesc') },
    { href: '/security-token', icon: 'token-icon', label: t('svcToken'), desc: t('svcTokenDesc') },
    { href: '/recruit-a-friend', icon: 'recruit-a-friend-icon', label: t('svcRecruit'), desc: t('svcRecruitDesc') },
    { href: '/rename-guild', icon: 'rename-guild-icon', label: t('svcRenameGuild'), desc: t('svcRenameGuildDesc') },
    { href: '/vote-points', icon: 'vote-icon', label: t('svcVote'), desc: t('svcVoteDesc') },
    { href: '/d-points', icon: 'dnt-icon', label: t('svcDPoints'), desc: t('svcDPointsDesc') },
    // Las que tenemos y no están en la lista, al final:
    { href: '/change-email', icon: 'password-icon', label: t('svcChangeEmail'), desc: t('svcChangeEmailDesc') },
    // Panel de administración: una tool-button más dentro de «Opciones de cuenta» (solo admins).
    ...(isAdmin ? [{ href: '/admin', icon: 'store-icon', label: `🛡️ ${t('adminPanel')}`, desc: t('adminPanelDesc') }] : []),
  ]
  const characterTools: Tool[] = [
    { href: '/unstuck-character', icon: 'unstuck-icon', label: t('svcUnstuck'), desc: t('svcUnstuckDesc') },
    { href: '/revive-character', icon: 'revive-icon', label: t('svcRevive'), desc: t('svcReviveDesc') },
    { href: '/rename-character', icon: 'rename-icon', label: t('svcRename'), desc: t('svcRenameDesc') },
    { href: '/customize-character', icon: 'customize-icon', label: t('svcCustomize'), desc: t('svcCustomizeDesc') },
    { href: '/change-race-character', icon: 'change-race-icon', label: t('svcChangeRace'), desc: t('svcChangeRaceDesc') },
    { href: '/change-faction-character', icon: 'change-faction-icon', label: t('svcChangeFaction'), desc: t('svcChangeFactionDesc') },
    { href: '/level-up-character', icon: 'level-up-icon', label: t('svcLevelUp'), desc: t('svcLevelUpDesc') },
    { href: '/gold-character', icon: 'gold-icon', label: t('svcGold'), desc: t('svcGoldDesc') },
    { href: '/quest-character', icon: 'quest-icon', label: t('svcQuest'), desc: t('svcQuestDesc') },
    { href: '/transfer-character', icon: 'tranfer-char-icon', label: t('svcTransfer'), desc: t('svcTransferDesc') },
    { href: '/restore-character', icon: 'restore-icon', label: t('svcRestoreChar'), desc: t('svcRestoreCharDesc') },
    { href: '/restore-items', icon: 'prox-icon', label: t('svcRestoreItems'), desc: t('svcRestoreItemsDesc') },
    // La tienda lleva el reino en la URL (/store-<slug>): lo calcula el server.
    { href: storeHref, icon: 'store-icon', label: t('svcStoreItems'), desc: t('svcStoreItemsDesc') },
    { href: '/send-gift', icon: 'send-gift-icon', label: t('svcSendGift'), desc: t('svcSendGiftDesc') },
  ]
  const historyTools: Tool[] = [
    { href: '/points-history', icon: 'pointsh-icon', label: t('svcPointsHistory'), desc: t('svcPointsHistoryDesc') },
    { href: '/trans-history', icon: 'dnth-icon', label: t('svcTransHistory'), desc: t('svcTransHistoryDesc') },
    { href: '/ban-history', icon: 'banh-icon', label: t('svcBanHistory'), desc: t('svcBanHistoryDesc') },
    { href: '/security-history', icon: 'securityh-icon', label: t('svcSecurityHistory'), desc: t('svcSecurityHistoryDesc') },
  ]

  return (
    <div className="body-box-content-account">
      <Panel id="account-settings" arrow="fa-arrow-down-account" title={t('accountOptions')} tools={accountTools} />
      <Panel id="character-settings" arrow="fa-arrow-down-character" title={t('characterOptions')} tools={characterTools} />
      <Panel id="account-history" arrow="fa-arrow-down-history" title={t('historyOptions')} tools={historyTools} />
    </div>
  )
}

function Panel({ id, arrow, title, tools, defaultOpen = false }: { id: string; arrow: string; title: string; tools: Tool[]; defaultOpen?: boolean }) {
  const [open, setOpen] = useState(defaultOpen)
  const rows: Tool[][] = []
  for (let i = 0; i < tools.length; i += 2) rows.push(tools.slice(i, i + 2))

  return (
    <>
      <div id={id} onClick={() => setOpen((v) => !v)}>
        {title} <i className={`fas fa-arrow-down ${arrow} ${open ? 'rotate' : 'rotate2'}`} />
      </div>
      <div id={`${id}-panel`} style={{ display: open ? 'block' : 'none' }}>
        <table className="max-center-table fixed-layout-table">
          <tbody>
            {rows.map((pair, i) => (
              <tr key={i}>
                {pair.map((it) => (
                  <td key={it.href}>
                    <Link href={it.href}>
                      <div className="tool-button">
                        <div className={`acc-icon ${it.icon}`}></div>
                        <div className="tool-button-div">
                          <span className={`first-brown shadow${it.labelClass ? ` ${it.labelClass}` : ''}`}>{it.label}</span>
                          <br />
                          <span className="second-brown shadow">{it.desc}</span>
                        </div>
                      </div>
                    </Link>
                  </td>
                ))}
                {pair.length === 1 && <td />}
              </tr>
            ))}
          </tbody>
        </table>
        <br />
      </div>
    </>
  )
}
