import type { Metadata } from 'next'
import Image from 'next/image'
import Link from 'next/link'
import { getTranslations } from 'next-intl/server'
import { BadgeCheck } from 'lucide-react'
import { getBrandList } from '@/lib/db/queries/getBrandDetail'
import { getDefaultLanguage, getLanguages } from '@/lib/db/queries/getlanguages'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { buildLocalizedPath } from '@/lib/i18n/buildLocalizedPath'
import Container from '@/components/frontend/Container'
import OtherHeader from '@/components/frontend/OtherHeader'

const APP_URL = (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000').replace(/\/$/, '')

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

export async function generateMetadata({ params }: BrandsPageProps): Promise<Metadata> {
  const { locale } = await params
  const [t, defaultLanguage, siteInfo, languages] = await Promise.all([
    getTranslations({ locale, namespace: 'BrandPage' }),
    getDefaultLanguage(),
    getSiteInfo(),
    getLanguages(),
  ])

  const defaultLocale = defaultLanguage?.code ?? 'en'
  const canonicalPath = buildLocalizedPath(locale, defaultLocale, '/brands')
  const title = `${t('indexMetaTitle')} | ${siteInfo.siteName}`
  const description = t('indexMetaDescription', { siteName: siteInfo.siteName })

  const languageAlternates: Record<string, string> = {}
  for (const lang of languages) {
    languageAlternates[lang.code] = `${APP_URL}${buildLocalizedPath(lang.code, defaultLocale, '/brands')}`
  }

  return {
    title,
    description,
    alternates: {
      canonical: `${APP_URL}${canonicalPath}`,
      languages: {
        ...languageAlternates,
        'x-default': `${APP_URL}${buildLocalizedPath(defaultLocale, defaultLocale, '/brands')}`,
      },
    },
    openGraph: {
      title,
      description,
      siteName: siteInfo.siteName,
      url: `${APP_URL}${canonicalPath}`,
      type: 'website',
    },
    twitter: { card: 'summary', title, description },
  }
}

// Server Component: every active brand with at least one browsable product
// (getBrandList — cached, tag-invalidated, see DATA_FETCHING_PATTERN.md),
// each linking to its /brand/[slug] listing. No interactivity, so no client
// component.
export default async function BrandsPage({ params }: BrandsPageProps) {
  const { locale } = await params
  const [brands, t] = await Promise.all([
    getBrandList(locale),
    getTranslations({ locale, namespace: 'BrandPage' }),
  ])

  return (
    <Container className="mt-4">
      <OtherHeader
        title={t('indexTitle')}
        description={t('indexDescription')}
        badgeText={t('badge')}
      />

      {brands.length === 0 ? (
        <div className="text-center py-16">
          <p className="text-gray-custom">{t('indexEmpty')}</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4 pb-12">
          {brands.map((brand) => (
            <Link
              key={brand.id}
              href={`/brand/${brand.slug}`}
              className="group bg-white rounded-2xl p-4 shadow-sm hover:shadow-lg transition-all flex flex-col items-center text-center gap-3"
            >
              <div className="relative w-20 h-20 flex items-center justify-center">
                {brand.logoUrl ? (
                  <Image
                    src={brand.logoUrl}
                    alt={brand.altText || brand.name}
                    fill
                    sizes="80px"
                    className="object-contain"
                  />
                ) : (
                  <BadgeCheck size={36} className="text-primary" />
                )}
              </div>
              <div className="min-w-0 w-full">
                <p className="font-semibold text-dark truncate group-hover:text-primary transition-colors">{brand.name}</p>
                <p className="text-xs text-gray-custom">{t('productsCount', { count: brand.productCount })}</p>
              </div>
            </Link>
          ))}
        </div>
      )}
    </Container>
  )
}
