import type { Metadata } from 'next'
import { setRequestLocale, getTranslations } from 'next-intl/server'
import { redirect, Link } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getSanctions, type Sanction } from '@/lib/ban-history'
import { PageShell } from '@/components/PageShell'
import { ServiceBox } from '@/components/ServiceBox'

export const dynamic = 'force-dynamic'

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }): Promise<Metadata> {
  const { locale } = await params
  const t = await getTranslations({ locale, namespace: 'History' })
  return { title: t('ban.pageTitle') }
}

/** Fecha en formato DD-MM-YYYY HH:MM:SS. */
function fmt(d: Date): string {
  const p = (n: number) => String(n).padStart(2, '0')
  return `${p(d.getDate())}-${p(d.getMonth() + 1)}-${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
}

/** Caja con la tabla de sanciones (baneos o muteos), o el vacío del diseño. */
async function SanctionBox({
  title,
  emptyText,
  rows,
  showScope,
}: {
  title: string
  emptyText: string
  rows: Sanction[]
  showScope: boolean
}) {
  const t = await getTranslations('History')
  return (
    <div className="box-content">
      <div className="title-box-content">
        <h2>{title}</h2>
      </div>
      <div className="body-box-content info-box-light">
        {rows.length === 0 ? (
          <table className="max-center-table">
            <tbody>
              <tr>
                <td className="centered">
                  <span>{emptyText}</span>
                </td>
              </tr>
            </tbody>
          </table>
        ) : (
          <table className="max-center-table">
            <tbody>
              <tr>
                {showScope && <th>{t('ban.thScope')}</th>}
                <th>{t('ban.thReason')}</th>
                <th>{t('ban.thBy')}</th>
                <th>{t('ban.thDate')}</th>
                <th>{t('ban.thExpires')}</th>
                <th>{t('ban.thStatus')}</th>
              </tr>
              {rows.map((s, i) => (
                <tr key={i}>
                  {showScope && (
                    <td>
                      <span>
                        {s.scopeKey === 'character'
                          ? t('ban.scope.character', { name: s.scopeName })
                          : t(`ban.scope.${s.scopeKey}`)}
                      </span>
                    </td>
                  )}
                  <td>
                    <span>{s.reason}</span>
                  </td>
                  <td>
                    <span>{s.by}</span>
                  </td>
                  <td>
                    <span>{fmt(s.date)}</span>
                  </td>
                  <td>
                    <span>{s.expires ? fmt(s.expires) : t('ban.permanent')}</span>
                  </td>
                  <td>
                    <span className={s.active ? 'red-info2' : 'green-info2'}>{t(`ban.status.${s.statusKey}`)}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}

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

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

  const { bans, mutes } = await getSanctions(session.accountId!, session.bnetId)

  return (
    <PageShell title={t('ban.pageTitle')}>
      <ServiceBox>
        <br />
        <p>{t('ban.intro1')}</p>
        <p>
          {t.rich('ban.intro2', { s: (c) => <span className="red-info2">{c}</span> })}
        </p>
        <p>{t('ban.intro3')}</p>
        <br />
        <div className="restore-item-table">
          <p>
            <i className="fas fa-exclamation-triangle"></i> <span>{t('ban.important')}</span>
          </p>
          <p>
            {t('ban.autoBlock1')}
          </p>
          <p>
            {t('ban.autoBlock2')}
          </p>
        </div>
        <br />
        <p>
          {t.rich('ban.claim', { link: (c) => <Link href="/forum">{c}</Link> })}
        </p>
      </ServiceBox>

      <SanctionBox title={t('ban.bansTitle')} emptyText={t('ban.noBans')} rows={bans} showScope />
      <SanctionBox title={t('ban.mutesTitle')} emptyText={t('ban.noMutes')} rows={mutes} showScope={false} />
    </PageShell>
  )
}
