import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import { ExternalLink } from 'lucide-react'
import { getBrandDetail, type BrandDetail } from '@/lib/db/queries/getBrandDetail'
import { getProductCatalog, getCatalogFacets, getCatalogPriceBounds } from '@/lib/db/queries/getProductCatalog'
import { getDefaultLanguage } from '@/lib/db/queries/getlanguages'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { buildLocalizedPath } from '@/lib/i18n/buildLocalizedPath'
import { fromSearchParams, parseCatalogParams, type PageSearchParams } from '@/lib/catalog/parseCatalogParams'
import JsonLd from '@/components/frontend/seo/JsonLd'
import CatalogBrowser from '@/components/frontend/catalog/CatalogBrowser'

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

interface BrandPageProps {
  params: Promise<{ locale: string; slug: string }>
  searchParams: Promise<PageSearchParams>
}

// Same idempotent decode as category/[slug]/page.tsx — the [slug] segment
// sometimes arrives still percent-encoded for non-ASCII (Urdu/Arabic) slugs.
function decodeSlug(slug: string): string {
  try {
    return decodeURIComponent(slug)
  } catch {
    return slug
  }
}

function stripHtml(html: string): string {
  return html.replace(/<[^>]+>/g, '').trim()
}

function buildAlternatePaths(brand: BrandDetail, defaultLocale: string): Record<string, string> {
  const paths: Record<string, string> = {}
  for (const alt of brand.alternateLocales) {
    paths[alt.locale] = buildLocalizedPath(alt.locale, defaultLocale, `/brand/${alt.slug}`)
  }
  return paths
}

export async function generateMetadata({ params }: BrandPageProps): Promise<Metadata> {
  const { locale, slug } = await params
  const [brand, defaultLanguage, siteInfo] = await Promise.all([
    getBrandDetail(decodeSlug(slug), locale),
    getDefaultLanguage(),
    getSiteInfo(),
  ])
  if (!brand) return {}

  const defaultLocale = defaultLanguage?.code ?? 'en'
  const alternatePaths = buildAlternatePaths(brand, defaultLocale)
  const canonicalPath = buildLocalizedPath(locale, defaultLocale, `/brand/${brand.slug}`)

  const title = brand.metaTitle || brand.name
  const description =
    brand.metaDescription ||
    (brand.description ? stripHtml(brand.description).slice(0, 160) : undefined)
  const ogImages = brand.logoUrl ? [{ url: brand.logoUrl, alt: brand.altText || brand.name }] : undefined

  return {
    title: `${title} | ${siteInfo.siteName}`,
    description,
    alternates: {
      canonical: `${APP_URL}${canonicalPath}`,
      languages: {
        ...Object.fromEntries(
          Object.entries(alternatePaths).map(([loc, path]) => [loc, `${APP_URL}${path}`]),
        ),
        'x-default': `${APP_URL}${alternatePaths[defaultLocale] ?? canonicalPath}`,
      },
    },
    openGraph: {
      title,
      description,
      siteName: siteInfo.siteName,
      url: `${APP_URL}${canonicalPath}`,
      images: ogImages,
      type: 'website',
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: ogImages?.map((img) => img.url),
    },
    robots: brand.isIndexable ? { index: true, follow: true } : { index: false, follow: true },
  }
}

// Auto-generated Schema.org Brand markup from real data — always rendered;
// any raw JSON-LD an admin entered on the brand (SchemaEditor, brand_schemas
// column) is rendered alongside it, additively.
function buildBrandSchema(brand: BrandDetail, canonicalUrl: string): Record<string, unknown> {
  return {
    '@context': 'https://schema.org',
    '@type': 'Brand',
    name: brand.name,
    url: canonicalUrl,
    logo: brand.logoUrl ?? undefined,
    description: brand.description ? stripHtml(brand.description) : undefined,
    sameAs: brand.websiteUrl ? [brand.websiteUrl] : undefined,
  }
}

// Server Component: real brand (name/description/SEO/logo) via
// getBrandDetail.ts, real filtered/sorted/paginated products scoped to this
// one brand via getProductCatalog.ts (the same query /products and
// /category/[slug] use, pinned to a brand), plus this brand's own category /
// attribute-option facets — see DATA_FETCHING_PATTERN.md. CatalogBrowser
// only owns the interactive filter/sort/page navigation.
export default async function BrandPage({ params, searchParams }: BrandPageProps) {
  const { locale, slug } = await params
  const sp = await searchParams

  const [brand, defaultLanguage, t] = await Promise.all([
    getBrandDetail(decodeSlug(slug), locale),
    getDefaultLanguage(),
    getTranslations({ locale, namespace: 'BrandPage' }),
  ])
  if (!brand) notFound()

  // Brand slugs are per-language (brand_translations.slug) — register the
  // real per-locale URLs with the language switcher, same as category pages.
  const defaultLocale = defaultLanguage?.code ?? 'en'
  const alternatePaths = buildAlternatePaths(brand, defaultLocale)
  const canonicalUrl = `${APP_URL}${buildLocalizedPath(locale, defaultLocale, `/brand/${brand.slug}`)}`

  // The brand itself is pinned; a ?brand= in the URL is ignored here.
  const filters = { ...parseCatalogParams(fromSearchParams(sp)), brandSlugs: [brand.slug] }

  const [catalog, facets, priceBounds] = await Promise.all([
    getProductCatalog(locale, { ...filters, perPage: PER_PAGE }),
    getCatalogFacets(locale, { brandId: brand.id }),
    getCatalogPriceBounds({ brandId: brand.id }),
  ])

  const schemas = [buildBrandSchema(brand, canonicalUrl), ...Object.values(brand.schemas)] as Record<string, unknown>[]

  return (
    <>
      <JsonLd data={schemas} />
      <CatalogBrowser
        header={{
          title: brand.name,
          description: brand.description ? stripHtml(brand.description) : undefined,
          badgeText: t('badge'),
          logoUrl: brand.logoUrl,
          iconAlt: brand.altText || brand.name,
        }}
        intro={
          brand.websiteUrl ? (
            <div className="-mt-4 mb-2 flex justify-end">
              <a
                href={brand.websiteUrl}
                target="_blank"
                rel="noopener noreferrer nofollow"
                className="inline-flex items-center gap-1.5 text-sm text-primary hover:underline"
              >
                {t('visitWebsite')}
                <ExternalLink size={14} />
              </a>
            </div>
          ) : undefined
        }
        pinned={{ brand: brand.slug }}
        perPage={PER_PAGE}
        products={catalog.products}
        total={catalog.total}
        totalPages={catalog.totalPages}
        facets={facets}
        priceBounds={priceBounds}
        initialFilters={filters}
        alternatePaths={alternatePaths}
        defaultLocale={defaultLocale}
      />
    </>
  )
}
