'use client'

import Image from 'next/image'
import { useEffect, useRef, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import Container from '@/components/frontend/Container'
import OtherHeader from '@/components/frontend/OtherHeader'
import FilterSidebar, { type FilterSection } from '@/components/frontend/FilterSidebar'
import PriceRangeFilter from '@/components/frontend/PriceRangeFilter'
import RatingFilter from '@/components/frontend/RatingFilter'
import ActiveFilters, { type FilterBadge } from '@/components/frontend/ActiveFilters'
import SortDropdown, { type SortOption } from '@/components/frontend/SortDropdown'
import Pagination from '@/components/frontend/Pagination'
import ProductCard from '@/components/frontend/ProductCard'
import { useLocaleAlternatesStore } from '@/store/localeAlternatesStore'
import { useCurrencyStore } from '@/store/currencyStore'
import type {
  CatalogFacets,
  CatalogProduct,
  PriceBounds,
  ProductCatalogSort,
} from '@/lib/db/queries/getProductCatalog'
import type { CatalogQueryFilters } from '@/lib/catalog/parseCatalogParams'

export interface CatalogHeader {
  title: string
  subtitle?: string
  description?: string
  badgeText?: string
  iconUrl?: string | null
  iconAlt?: string
  // Brand pages: the logo shown whole on a white tile (not the small icon)
  logoUrl?: string | null
}

interface CatalogBrowserProps {
  header: CatalogHeader
  // Extra server-rendered content under the header (e.g. a brand's website link).
  intro?: React.ReactNode
  // A listing pinned to one category or brand — always sent with every
  // refetch; that dimension's own filter section is not shown.
  pinned?: { category?: string; brand?: string }
  perPage: number
  products: CatalogProduct[]
  total: number
  totalPages: number
  facets: CatalogFacets
  priceBounds: PriceBounds
  initialFilters: CatalogQueryFilters
  // locale code -> this page's own URL in that language (slugs differ per
  // language for category/brand pages). Registered with the language
  // switcher — see localeAlternatesStore.ts. /products has no per-locale
  // slug, but registering it still prevents a stale registration left by a
  // previously visited page from leaking into a language switch made here.
  alternatePaths: Record<string, string>
  defaultLocale: string
}

type QueryState = {
  search: string
  category: string[]
  brand: string[]
  options: string[]
  minPrice: number | null
  maxPrice: number | null
  rating: number | null
  inStock: boolean
  sort: ProductCatalogSort
  page: number
}

function toggle(list: string[], value: string): string[] {
  return list.includes(value) ? list.filter((v) => v !== value) : [...list, value]
}

function FacetCheckboxList({
  items,
  selected,
  onToggle,
}: {
  items: { key: string; label: string; count: number }[]
  selected: string[]
  onToggle: (key: string) => void
}) {
  return (
    <div className="space-y-2 max-h-60 overflow-y-auto pe-1">
      {items.map((item) => (
        <label key={item.key} className="flex items-center justify-between cursor-pointer gap-2">
          <div className="flex items-center gap-2 min-w-0">
            <input
              type="checkbox"
              checked={selected.includes(item.key)}
              onChange={() => onToggle(item.key)}
              className="w-4 h-4 shrink-0 rounded border-gray-300 text-primary focus:ring-primary"
            />
            <span className="text-sm text-dark truncate">{item.label}</span>
          </div>
          <span className="text-xs text-gray-custom shrink-0">{item.count}</span>
        </label>
      ))}
    </div>
  )
}

// The storefront's one product-listing UI — /products, /category/[slug] and
// /brand/[slug] all render it. Facets (categories/brands/attribute options
// with real counts) and price bounds are fetched once, server-side, by the
// page (see DATA_FETCHING_PATTERN.md); the product list itself is re-fetched
// from /api/frontend/products on every filter/sort/page change via plain
// client state, deliberately WITHOUT touching the URL/query-string (the URL
// only ever reflects the very first server-rendered load, e.g. a
// direct/shared link with filters baked in) — no client-side array
// filtering either way, just where the "refetch" is triggered from.
export default function CatalogBrowser({
  header,
  intro,
  pinned = {},
  perPage,
  products: initialProducts,
  total: initialTotal,
  totalPages: initialTotalPages,
  facets,
  priceBounds,
  initialFilters,
  alternatePaths,
  defaultLocale,
}: CatalogBrowserProps) {
  const t = useTranslations('ProductsPage')
  const locale = useLocale()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)

  const setAlternates = useLocaleAlternatesStore((s) => s.setAlternates)
  const clearAlternates = useLocaleAlternatesStore((s) => s.clearAlternates)

  useEffect(() => {
    setAlternates(alternatePaths, defaultLocale)
    return () => clearAlternates()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [alternatePaths, defaultLocale])

  const [products, setProducts] = useState(initialProducts)
  const [total, setTotal] = useState(initialTotal)
  const [totalPages, setTotalPages] = useState(initialTotalPages)
  const [isLoading, setIsLoading] = useState(false)

  const [query, setQuery] = useState<QueryState>(() => ({
    search: initialFilters.search ?? '',
    category: pinned.category ? [] : initialFilters.categorySlugs ?? [],
    brand: pinned.brand ? [] : initialFilters.brandSlugs ?? [],
    options: initialFilters.optionIds ?? [],
    minPrice: initialFilters.minPrice ?? null,
    maxPrice: initialFilters.maxPrice ?? null,
    rating: initialFilters.minRating ?? null,
    inStock: initialFilters.inStockOnly ?? false,
    sort: initialFilters.sort ?? 'newest',
    page: initialFilters.page,
  }))

  // Guards against an older, slower request resolving after a newer one and
  // clobbering fresher results (e.g. spamming the price slider).
  const requestSeq = useRef(0)

  const minPrice = query.minPrice ?? priceBounds.min
  const maxPrice = query.maxPrice ?? priceBounds.max
  const priceStep = Math.max(1, Math.round((priceBounds.max - priceBounds.min) / 100) || 1)

  const applyFilters = async (overrides: Partial<QueryState>) => {
    const next: QueryState = { ...query, page: 1, ...overrides }
    setQuery(next)

    const seq = ++requestSeq.current
    setIsLoading(true)

    const params = new URLSearchParams()
    params.set('locale', locale)
    if (next.search) params.set('q', next.search)
    const categories = pinned.category ? [pinned.category] : next.category
    const brands = pinned.brand ? [pinned.brand] : next.brand
    if (categories.length > 0) params.set('category', categories.join(','))
    if (brands.length > 0) params.set('brand', brands.join(','))
    if (next.options.length > 0) params.set('options', next.options.join(','))
    if (next.minPrice !== null) params.set('minPrice', String(next.minPrice))
    if (next.maxPrice !== null) params.set('maxPrice', String(next.maxPrice))
    if (next.rating !== null) params.set('rating', String(next.rating))
    if (next.inStock) params.set('inStock', '1')
    params.set('sort', next.sort)
    params.set('page', String(next.page))
    params.set('perPage', String(perPage))

    try {
      const res = await fetch(`/api/frontend/products?${params.toString()}`)
      const json = await res.json()
      if (seq !== requestSeq.current) return // a newer request already landed
      if (json.success) {
        setProducts(json.data.products)
        setTotal(json.data.total)
        setTotalPages(json.data.totalPages)
      }
    } catch {
      // Silent — the previous product list simply stays on screen.
    } finally {
      if (seq === requestSeq.current) setIsLoading(false)
    }
  }

  const sortOptions: SortOption[] = [
    { value: 'popular', label: t('sortPopular') },
    { value: 'newest', label: t('sortNewest') },
    { value: 'price_asc', label: t('sortPriceAsc') },
    { value: 'price_desc', label: t('sortPriceDesc') },
    { value: 'rating', label: t('sortRating') },
  ]

  // option id -> "Attribute: Value" for its active-filter badge
  const optionLabels = new Map<string, string>()
  for (const attribute of facets.attributes) {
    for (const option of attribute.options) {
      optionLabels.set(option.id, `${attribute.name}: ${option.value}`)
    }
  }

  const activeFiltersList: FilterBadge[] = [
    ...(query.search ? [{ id: 'search', label: `"${query.search}"`, type: 'search' }] : []),
    ...query.category.map((slug) => ({
      id: `cat-${slug}`,
      label: facets.categories.find((c) => c.slug === slug)?.name ?? slug,
      type: 'category',
      value: slug,
    })),
    ...query.brand.map((slug) => ({
      id: `brand-${slug}`,
      label: facets.brands.find((b) => b.slug === slug)?.name ?? slug,
      type: 'brand',
      value: slug,
    })),
    ...query.options
      .filter((id) => optionLabels.has(id))
      .map((id) => ({ id: `opt-${id}`, label: optionLabels.get(id)!, type: 'option', value: id })),
    ...(query.minPrice !== null ? [{ id: 'price-min', label: `Min: ${formatAmount(query.minPrice)}`, type: 'priceMin' }] : []),
    ...(query.maxPrice !== null ? [{ id: 'price-max', label: `Max: ${formatAmount(query.maxPrice)}`, type: 'priceMax' }] : []),
    ...(query.rating !== null ? [{ id: 'rating', label: `${query.rating}+ Stars`, type: 'rating' }] : []),
    ...(query.inStock ? [{ id: 'stock', label: t('inStockOnly'), type: 'inStock' }] : []),
  ]

  const removeFilter = (_id: string, type: string, value?: string) => {
    switch (type) {
      case 'search': applyFilters({ search: '' }); break
      case 'category': applyFilters({ category: query.category.filter((c) => c !== value) }); break
      case 'brand': applyFilters({ brand: query.brand.filter((b) => b !== value) }); break
      case 'option': applyFilters({ options: query.options.filter((o) => o !== value) }); break
      case 'priceMin': applyFilters({ minPrice: null }); break
      case 'priceMax': applyFilters({ maxPrice: null }); break
      case 'rating': applyFilters({ rating: null }); break
      case 'inStock': applyFilters({ inStock: false }); break
    }
  }

  const clearAllFilters = () => {
    applyFilters({
      search: '', category: [], brand: [], options: [],
      minPrice: null, maxPrice: null, rating: null, inStock: false, sort: 'newest',
    })
  }

  const filterSections: FilterSection[] = [
    ...(!pinned.category && facets.categories.length > 0
      ? [{
          id: 'categories',
          title: t('filterCategories'),
          defaultExpanded: true,
          content: (
            <FacetCheckboxList
              items={facets.categories.map((c) => ({ key: c.slug, label: c.name, count: c.productCount }))}
              selected={query.category}
              onToggle={(slug) => applyFilters({ category: toggle(query.category, slug) })}
            />
          ),
        }]
      : []),
    ...(!pinned.brand && facets.brands.length > 0
      ? [{
          id: 'brands',
          title: t('filterBrands'),
          defaultExpanded: true,
          content: (
            <FacetCheckboxList
              items={facets.brands.map((b) => ({ key: b.slug, label: b.name, count: b.productCount }))}
              selected={query.brand}
              onToggle={(slug) => applyFilters({ brand: toggle(query.brand, slug) })}
            />
          ),
        }]
      : []),
    {
      id: 'price',
      title: t('filterPrice'),
      defaultExpanded: true,
      content: (
        <PriceRangeFilter
          min={priceBounds.min}
          max={priceBounds.max}
          step={priceStep}
          values={[minPrice, maxPrice]}
          onChange={([newMin, newMax]) => applyFilters({ minPrice: newMin, maxPrice: newMax })}
        />
      ),
    },
    ...facets.attributes.map((attribute) => ({
      id: `attr-${attribute.id}`,
      title: attribute.name,
      defaultExpanded: true,
      content: (
        <FacetCheckboxList
          items={attribute.options.map((o) => ({ key: o.id, label: o.value, count: o.productCount }))}
          selected={query.options}
          onToggle={(id) => applyFilters({ options: toggle(query.options, id) })}
        />
      ),
    })),
    {
      id: 'rating',
      title: t('filterRating'),
      defaultExpanded: true,
      content: <RatingFilter value={query.rating} onChange={(rating) => applyFilters({ rating })} />,
    },
    {
      id: 'inStock',
      title: t('filterAvailability'),
      defaultExpanded: true,
      content: (
        <label className="flex items-center justify-between cursor-pointer">
          <span className="text-sm text-dark">{t('inStockOnly')}</span>
          <div className="relative">
            <input
              type="checkbox"
              checked={query.inStock}
              onChange={(e) => applyFilters({ inStock: e.target.checked })}
              className="sr-only peer"
            />
            <div className="w-10 h-5 bg-gray-200 rounded-full peer-checked:bg-primary transition-colors"></div>
            <div
              className={`absolute left-0.5 top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${query.inStock ? 'translate-x-5' : ''}`}
            />
          </div>
        </label>
      ),
    },
  ]

  const headerIcon = header.iconUrl ? (
    <Image src={header.iconUrl} alt={header.iconAlt || header.title} width={20} height={20} className="rounded object-cover" />
  ) : undefined

  return (
    <Container className="mt-4">
      <OtherHeader
        title={header.title}
        subtitle={header.subtitle}
        description={header.description}
        icon={headerIcon}
        logo={header.logoUrl ? { url: header.logoUrl, alt: header.iconAlt || header.title } : undefined}
        badgeText={header.badgeText}
        totalProducts={total}
      />

      {intro}

      <div className="flex flex-col md:flex-row gap-8 py-8">
        <FilterSidebar
          sections={filterSections}
          activeFiltersCount={activeFiltersList.length}
          onClearAll={clearAllFilters}
        />

        <div className="flex-1 min-w-0">
          <ActiveFilters filters={activeFiltersList} onRemove={removeFilter} onClearAll={clearAllFilters} />

          <SortDropdown
            options={sortOptions}
            value={query.sort}
            onChange={(value) => applyFilters({ sort: value as ProductCatalogSort })}
            totalItems={total}
          />

          {products.length === 0 ? (
            <div className="text-center py-16">
              <div className="text-6xl mb-4">🛒</div>
              <h3 className="text-xl font-semibold text-dark mb-2">{t('emptyTitle')}</h3>
              <p className="text-gray-custom">{t('emptyDescription')}</p>
            </div>
          ) : (
            <div className={`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 transition-opacity ${isLoading ? 'opacity-50' : ''}`}>
              {products.map((product, index) => (
                <ProductCard
                  key={product.id}
                  priority={index < 3}
                  id={product.id}
                  title={product.title}
                  price={product.price}
                  oldPrice={product.oldPrice}
                  rating={product.ratingAverage}
                  reviews={product.ratingCount}
                  image={product.imageUrl ?? '📦'}
                  slug={product.slug}
                  productType={product.type}
                  brand={product.brand}
                />
              ))}
            </div>
          )}

          <Pagination
            currentPage={query.page}
            totalPages={totalPages}
            onPageChange={(newPage) => applyFilters({ page: newPage })}
          />
        </div>
      </div>
    </Container>
  )
}
