import type { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import { getProductCatalog, getCatalogCategories, getCatalogPriceBounds, type ProductCatalogSort } from '@/lib/db/queries/getProductCatalog'
import { getDefaultLanguage, getLanguages } from '@/lib/db/queries/getlanguages'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { buildLocalizedPath } from '@/lib/i18n/buildLocalizedPath'
import ProductsPageClient from '@/components/frontend/products/ProductsPageClient'

const APP_URL = (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000').replace(/\/$/, '')
const PER_PAGE = 12
const SORT_VALUES: ProductCatalogSort[] = ['newest', 'price_asc', 'price_desc', 'rating', 'popular']

interface ProductsPageProps {
  params: Promise<{ locale: string }>
  searchParams: Promise<{
    category?: string
    minPrice?: string
    maxPrice?: string
    rating?: string
    inStock?: string
    sort?: string
    page?: string
  }>
}

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

  const defaultLocale = defaultLanguage?.code ?? 'en'
  const canonicalPath = buildLocalizedPath(locale, defaultLocale, '/products')
  const title = `${t('metaTitle')} | ${siteInfo.siteName}`
  const description = t('metaDescription')

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

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

// Server Component: real DB-backed catalog — filtering, sorting, pagination,
// category counts and the price slider's bounds are all real SQL, driven
// entirely by the URL's query string (see getProductCatalog.ts /
// DATA_FETCHING_PATTERN.md, modeled on /blogs' searchParams-driven listing).
// ProductsPageClient only owns the interactive bits (updating the URL on a
// filter/sort/page change, the mobile filter drawer).
export default async function ProductsPage({ params, searchParams }: ProductsPageProps) {
  const { locale } = await params
  const sp = await searchParams

  const categorySlugs = sp.category ? sp.category.split(',').map((s) => s.trim()).filter(Boolean) : []
  const minPrice = sp.minPrice !== undefined ? Number(sp.minPrice) : undefined
  const maxPrice = sp.maxPrice !== undefined ? Number(sp.maxPrice) : undefined
  const minRating = sp.rating !== undefined ? Number(sp.rating) : undefined
  const inStockOnly = sp.inStock === '1'
  const sort: ProductCatalogSort = SORT_VALUES.includes(sp.sort as ProductCatalogSort) ? (sp.sort as ProductCatalogSort) : 'newest'
  const page = Math.max(1, Number(sp.page) || 1)

  const [catalog, categories, priceBounds] = await Promise.all([
    getProductCatalog(locale, {
      categorySlugs: categorySlugs.length > 0 ? categorySlugs : undefined,
      minPrice: Number.isFinite(minPrice) ? minPrice : undefined,
      maxPrice: Number.isFinite(maxPrice) ? maxPrice : undefined,
      minRating: Number.isFinite(minRating) ? minRating : undefined,
      inStockOnly,
      sort,
      page,
      perPage: PER_PAGE,
    }),
    getCatalogCategories(locale),
    getCatalogPriceBounds(),
  ])

  return (
    <ProductsPageClient
      products={catalog.products}
      total={catalog.total}
      totalPages={catalog.totalPages}
      page={page}
      categories={categories}
      priceBounds={priceBounds}
      activeCategorySlugs={categorySlugs}
      activeMinPrice={Number.isFinite(minPrice) ? minPrice! : null}
      activeMaxPrice={Number.isFinite(maxPrice) ? maxPrice! : null}
      activeMinRating={Number.isFinite(minRating) ? minRating! : null}
      activeInStockOnly={inStockOnly}
      activeSort={sort}
    />
  )
}
