import type { Metadata } from 'next'
import { setRequestLocale, getTranslations } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getPaymentTransactions, type PaymentTx } from '@/lib/trans-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('trans.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())}`
}

function StatusBadge({ status }: { status: PaymentTx['status'] }) {
  return <span className={status === 'PAID' ? 'green-info2' : 'yellow-info'}>{status}</span>
}

/** Caja de una pasarela con su tabla de transacciones (o "No hay movimientos"). */
async function PlatformBox({
  name,
  logo,
  note,
  txs,
}: {
  name: string
  logo: string
  note: string
  txs: PaymentTx[]
}) {
  const t = await getTranslations('History')
  return (
    <div className="box-content">
      <div className="title-box-content">
        <h2>
          <img src={logo} alt={name} title={name} style={{ height: '22px', verticalAlign: 'middle', marginRight: '6px' }} /> {name}
        </h2>
      </div>
      <div className="body-box-content">
        <p>
          {t.rich('trans.paidNote', { s: (c) => <span className="green-info2">{c}</span> })}
        </p>
        <br />
        <p>
          <span className="red-info2">{t('trans.important')}</span> {note}
        </p>
        <br />
        {txs.length === 0 ? (
          <table className="max-center-table-aligned">
            <tbody>
              <tr>
                <td>
                  <span>{t('trans.noMovements')}</span>
                </td>
              </tr>
            </tbody>
          </table>
        ) : (
          <table className="max-center-table-aligned">
            <tbody>
              <tr>
                <th>{t('trans.thTxId')}</th>
                <th>{t('trans.thStatus')}</th>
                <th className="responsive-td">{t('trans.thConcept')}</th>
                <th>{t('trans.thCreatedAt')}</th>
                <th>{t('trans.thAmount')}</th>
              </tr>
              {txs.map((tx) => (
                <tr key={tx.id}>
                  <td className="long-td">
                    <span>{tx.id}</span>
                  </td>
                  <td>
                    <StatusBadge status={tx.status} />
                  </td>
                  <td className="responsive-td">
                    <span>{tx.conceptKey ? t(`points.concept.${tx.conceptKey}`, tx.conceptArgs) : tx.conceptRaw}</span>
                  </td>
                  <td>
                    <span>{fmt(tx.createdAt)}</span>
                  </td>
                  <td>
                    <span>{tx.amount.toFixed(2)} €</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}

const LOGO_BASE = '/nw-themes/nw-ryu/nw-images/nw-logos'

export default async function TransHistoryPage({ 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 txs = await getPaymentTransactions(session.accountId!)
  const stripe = txs.filter((t) => t.platform === 'Stripe')
  const sumup = txs.filter((t) => t.platform === 'SumUp')

  return (
    <PageShell title={t('trans.pageTitle')}>
      <ServiceBox>
        <br />
        <p>{t('trans.intro1')}</p>
        <br />
        <p>{t('trans.intro2')}</p>
        <p>
          {t.rich('trans.intro3', {
            mail: (c) => <a href="mailto:consultas@nightspire.gg">{c}</a>,
          })}
        </p>
      </ServiceBox>
      <br />
      <PlatformBox
        name="Stripe"
        logo={`${LOGO_BASE}/stripe-p-logo.svg`}
        note={t('trans.noteStripe')}
        txs={stripe}
      />
      <br />
      <hr />
      <br />
      <PlatformBox
        name="SumUp"
        logo={`${LOGO_BASE}/sumup-p-logo.svg`}
        note={t('trans.noteSumup')}
        txs={sumup}
      />
    </PageShell>
  )
}
