import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect, Link } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getAccountDashboard } from '@/lib/account'
import { isAdmin } from '@/lib/admin'
import { LogoutButton } from '@/components/LogoutButton'

export const dynamic = 'force-dynamic'

export default async function AccountPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Account')

  const session = await getSession()
  if (!session.bnetId) redirect({ href: '/login', locale })
  if (!session.username) redirect({ href: '/select-account', locale })

  const data = await getAccountDashboard(session)
  const admin = await isAdmin(session)

  const card = 'nw-card'

  return (
    <main className="mx-auto max-w-3xl px-4 py-8">
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold text-amber-500">{t('title')}</h1>
        <LogoutButton className="rounded border border-amber-900/60 px-3 py-1 text-sm text-amber-200 hover:text-amber-400" />
      </div>

      {admin && (
        <Link
          href="/admin"
          className="mb-6 flex items-center justify-between gap-3 rounded-lg border border-nw-gold/50 bg-nw-gold/10 px-4 py-3 text-sm font-semibold text-nw-gold-light transition hover:bg-nw-gold/20"
        >
          <span>🛡️ {t('adminPanel')}</span>
          <span aria-hidden>→</span>
        </Link>
      )}

      <div className="grid gap-4 sm:grid-cols-2">
        <section className={card}>
          <div className="space-y-1 text-sm">
            <p>{t('bnetAccount')}: <span className="text-amber-400">{data.bnetEmail}</span></p>
            <p>{t('gameAccount')}: <span className="text-amber-400">{data.gameAccount}</span></p>
            <p>
              {t('securityToken')}:{' '}
              <span className="text-amber-400">
                {data.securityTokenDate
                  ? `${t('requested')} — ${new Date(data.securityTokenDate).toLocaleString(locale)}`
                  : t('notRequested')}
              </span>
            </p>
          </div>
        </section>

        <section className={card}>
          <h2 className="mb-2 text-lg font-semibold">{t('points')}</h2>
          <div className="space-y-1 text-sm">
            <p>{t('dp')}: <span className="text-amber-400">{data.dp}</span></p>
            <p>{t('vp')}: <span className="text-amber-400">{data.vp}</span></p>
            <p>{t('battlepayCredits')}: <span className="text-amber-400">{data.battlepayCredits}</span></p>
          </div>
        </section>
      </div>

      <section className="mt-6">
        <h2 className="mb-3 text-lg font-semibold">{t('characters')}</h2>
        {data.characters.length === 0 ? (
          <p className="text-amber-200/70">{t('noCharacters')}</p>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 md:grid-cols-3">
            {data.characters.map((c) => (
              <div key={c.name} className={`${card} flex gap-3`}>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={c.imageUrl}
                  alt={c.raceName}
                  className="h-16 w-16 shrink-0 rounded-md object-cover ring-1 ring-nw-border/60"
                  loading="lazy"
                />
                <div className="min-w-0">
                  <p className={`truncate font-semibold class-${c.classCss}`}>{c.name}</p>
                  <p className="text-xs text-nw-muted">
                    {t('level')} {c.level} · {c.raceName} {c.className}
                  </p>
                  <p className="mt-1 flex items-center gap-1 text-xs text-amber-200/70" title={c.zone}>
                    <span aria-hidden>📍</span>
                    <span className="truncate">{c.zone}</span>
                  </p>
                  <p className="text-xs text-amber-200/60">
                    {c.gold}g {c.silver}s {c.copper}c
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      <ServicesPanel t={t} />
    </main>
  )
}

function ServicesPanel({ t }: { t: (k: string) => string }) {
  const groups: { title: string; items: { href: string; label: string }[] }[] = [
    {
      title: t('servicesTitle'),
      items: [
        { href: '/rename', label: t('svcRename') },
        { href: '/customize', label: t('svcCustomize') },
        { href: '/change-race', label: t('svcChangeRace') },
        { href: '/change-faction', label: t('svcChangeFaction') },
        { href: '/level-up', label: t('svcLevelUp') },
        { href: '/gold', label: t('svcGold') },
        { href: '/transfer', label: t('svcTransfer') },
      ],
    },
    {
      title: t('utilitiesTitle'),
      items: [
        { href: '/revive', label: t('svcRevive') },
        { href: '/unstuck', label: t('svcUnstuck') },
        { href: '/security-token', label: t('svcToken') },
      ],
    },
    {
      title: t('accountSettings'),
      items: [
        { href: '/change-password', label: t('svcChangePassword') },
        { href: '/change-email', label: t('svcChangeEmail') },
      ],
    },
    {
      title: t('communityTitle'),
      items: [
        { href: '/vote-points', label: t('svcVote') },
        { href: '/recruit', label: t('svcRecruit') },
        { href: '/battlepay', label: t('svcStore') },
      ],
    },
  ]

  return (
    <div className="mt-8 grid gap-4 sm:grid-cols-2">
      {groups.map((g) => (
        <section key={g.title} className="nw-card">
          <h2 className="mb-3 text-lg font-semibold text-nw-gold-light">{g.title}</h2>
          <ul className="space-y-1.5 text-sm">
            {g.items.map((it) => (
              <li key={it.href}>
                <Link href={it.href} className="text-sky-400 hover:text-amber-300 hover:underline">
                  {it.label}
                </Link>
              </li>
            ))}
          </ul>
        </section>
      ))}
    </div>
  )
}
