import type { Metadata } from 'next'
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getGameCharacters } from '@/lib/characters'
import { getStoreBalances } from '@/lib/store'
import { getRealmName } from '@/lib/realm'
import { wowheadWotlkHome } from '@/lib/wowhead'
import { PageShell } from '@/components/PageShell'
import { ServiceBox } from '@/components/ServiceBox'
import { StoreBrowser } from '@/components/StoreBrowser'
import { StoreNews } from '@/components/StoreNews'

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: 'Store' })
  return { title: t('title') }
}

export default async function StorePage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  setRequestLocale(locale)

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

  const [chars, balances, realm] = await Promise.all([
    getGameCharacters(session.accountId!),
    getStoreBalances(session.accountId!),
    getRealmName(),
  ])

  const t = await getTranslations('Store')

  return (
    <PageShell title={<>{t('title')} - <span className="blue-info">{realm.toUpperCase()}</span></>}>
      <ServiceBox>
        <br />
        <p>{t('infoTooltip')}</p>
        <p>
          {t.rich('infoDb', {
            link: (c) => (
              <a href={wowheadWotlkHome(locale)} target="_blank" rel="noopener noreferrer">
                {c}
              </a>
            ),
          })}
        </p>
        <br />
        <StoreNews />
      </ServiceBox>

      <StoreBrowser
        characters={chars.map((c) => ({ name: c.name, classCss: c.classCss }))}
        dp={balances.dp}
        vp={balances.vp}
        realm={realm}
      />
    </PageShell>
  )
}
