import type { Metadata } from 'next'
import { setRequestLocale, getTranslations } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getPointsHistory, getPointsBalances, type PointsMovement } from '@/lib/points-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('points.pageTitle') }
}

/** Fecha en formato DD-MM-YYYY HH:MM. */
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())}`
}

function methodClass(method: PointsMovement['method']): string {
  if (method === 'SumUp') return 'green-info'
  if (method === 'Stripe') return 'purple-info'
  return 'second-brown'
}

export default async function PointsHistoryPage({ 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 [movements, balances] = await Promise.all([
    getPointsHistory(session.accountId!),
    getPointsBalances(session.accountId!),
  ])

  return (
    <PageShell title={t('points.pageTitle')}>
      <ServiceBox>
        <br />
        <p>{t('points.intro1')}</p>
        <p>
          {t('points.intro2')}
        </p>
        <p>{t('points.intro3')}</p>
        <br />
      </ServiceBox>

      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('points.boxTitle')}</h2>
        </div>
        <div className="body-box-content">
          <p className="centered">
            {t('points.currentBalance')} <span className="yellow-info">{balances.dp} PD</span> ·{' '}
            <span className="purple-info">{balances.pv} PV</span>
          </p>
          <br />
          {movements.length === 0 ? (
            <table className="max-center-table-aligned2">
              <tbody>
                <tr>
                  <td>
                    <span>{t('points.noMovements')}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          ) : (
            <table className="max-center-table-aligned2">
              <thead>
                <tr>
                  <th>{t('points.thDate')}</th>
                  <th>{t('points.thConcept')}</th>
                  <th>{t('points.thMethod')}</th>
                  <th>PD</th>
                  <th>PV</th>
                  <th>{t('points.thAmount')}</th>
                  <th>{t('points.thStatus')}</th>
                </tr>
              </thead>
              <tbody>
                {movements.map((m, i) => (
                  <tr key={i}>
                    <td>{fmt(m.date)}</td>
                    <td>{m.conceptKey ? t(`points.concept.${m.conceptKey}`, m.conceptArgs) : m.conceptRaw}</td>
                    <td className={methodClass(m.method)}>
                      {m.method === 'vote' || m.method === 'promo' ? t(`points.method.${m.method}`) : m.method}
                    </td>
                    <td className="yellow-info">{m.pd != null ? `+${m.pd}` : '—'}</td>
                    <td className="purple-info">{m.pv != null ? `+${m.pv}` : '—'}</td>
                    <td>{m.amount != null ? `${m.amount.toFixed(2)} €` : '—'}</td>
                    <td>{t(`points.status.${m.status}`)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </PageShell>
  )
}
