import type { Metadata } from 'next'
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect, Link } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { is2faEnabled } from '@/lib/two-factor'
import { PageShell } from '@/components/PageShell'
import { TwoFactorLogin } from '@/components/TwoFactorLogin'

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: 'Misc' })
  return { title: t('twofaLogin.pageTitle') }
}

const IMG = '/nw-themes/nw-ryu/nw-images'

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

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

  const enabled = session.accountId ? await is2faEnabled(session.accountId) : false

  return (
    <PageShell title={t('twofaLogin.pageTitle')}>
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('twofaLogin.info')}</h2>
          <Link className="back-to-account" href="/my-account">{t('twofaLogin.backToAccount')}</Link>
          <Link className="back-to-account-responsive" href="/my-account">{t('twofaLogin.back')}</Link>
        </div>
        <div className="body-box-content justified">
          <br />
          <div className="twofa-login-info">
            <img
              className="twofa-login-preview"
              src={`${IMG}/nw-general/nw-authenticator-preview.png`}
              alt={t('twofaLogin.previewAlt')}
            />
            <div className="twofa-login-info-text">
              <p>{t.rich('twofaLogin.p1', { s: (c) => <span>{c}</span> })}</p>
              <br />
              <p>{t('twofaLogin.p2')}</p>
              <p>{t('twofaLogin.p3')}</p>
              <br />
              <p>{t('twofaLogin.p4')}</p>
              <br />
              <p><span>{t('twofaLogin.backupCodes')}</span></p>
              <p>{t('twofaLogin.p5')}</p>
              <p>{t('twofaLogin.p6')}</p>
              <p>{t('twofaLogin.p7')}</p>
              <p>{t('twofaLogin.p8')}</p>
              <br />
              <p>{t.rich('twofaLogin.requestToken', { link: (c) => <Link href="/security-token" target="_blank">{c}</Link> })}</p>
              <br />
            </div>
          </div>
          <fieldset>
            <legend>{t('twofaLogin.note')}</legend>
            <div className="separate2">
              <p>{t('twofaLogin.noteText')}</p>
            </div>
          </fieldset>

          <TwoFactorLogin enabled={enabled} />
        </div>
      </div>
    </PageShell>
  )
}
