import type { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import Container from '@/components/frontend/Container'
import ReferralHero from '@/components/frontend/referral/ReferralHero'
import ReferralHowItWorks from '@/components/frontend/referral/ReferralHowItWorks'
import { Link } from '@/i18n/navigation'
import { getReferralSettings } from '@/lib/db/queries/getReferralSettings'
import { getCurrencySettings } from '@/lib/db/queries/getCurrencySettings'
import { formatCurrency } from '@/lib/utils/currency'

interface ReferralPageProps {
  params: Promise<{ locale: string }>
}

export async function generateMetadata({ params }: ReferralPageProps): Promise<Metadata> {
  const { locale } = await params
  const t = await getTranslations({ locale, namespace: 'ReferralPage' })
  return { title: t('metaTitle'), description: t('metaDescription') }
}

// Server Component: the advertised reward comes from the same site_settings
// columns that actually pay referrers out (getReferralSettings.ts), instead of
// the made-up "5–10% / per-category" copy the page used to hardcode.
export default async function ReferralProgramPage({ params }: ReferralPageProps) {
  const { locale } = await params
  const [t, settings, currency] = await Promise.all([
    getTranslations({ locale, namespace: 'ReferralPage' }),
    getReferralSettings(),
    getCurrencySettings(),
  ])

  const reward = settings.rewardType === 'percentage'
    ? `${settings.rewardValue}%`
    : formatCurrency(settings.rewardValue, currency)
  const minOrder = settings.minOrderToEarn > 0 ? formatCurrency(settings.minOrderToEarn, currency) : null

  return (
    <>
      <ReferralHero enabled={settings.enabled} />
      <Container className="py-8">
        <ReferralHowItWorks reward={settings.enabled ? reward : null} />

        <div className="mt-8 bg-gradient-primary rounded-xl p-6 text-white text-center">
          {settings.enabled ? (
            <>
              <h3 className="text-xl font-bold mb-2">{t('bannerTitle', { reward })}</h3>
              <p className="text-white/90">
                {t('bannerBody', { reward })}
                {minOrder ? ` ${t('bannerMinOrder', { amount: minOrder })}` : ''}
              </p>
            </>
          ) : (
            <>
              <h3 className="text-xl font-bold mb-2">{t('pausedTitle')}</h3>
              <p className="text-white/90">{t('pausedBody')}</p>
            </>
          )}
          <Link
            href="/account/referrals"
            className="inline-block mt-4 bg-white text-primary px-6 py-2 rounded-lg font-semibold hover:shadow-md transition"
          >
            {t('cta')}
          </Link>
        </div>
      </Container>
    </>
  )
}
