'use client'

import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
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 { useCurrencyStore } from '@/store/currencyStore'
import type { CatalogProduct, CatalogCategory, PriceBounds, ProductCatalogSort } from '@/lib/db/queries/getProductCatalog'

interface ProductsPageClientProps {
  products: CatalogProduct[]
  total: number
  totalPages: number
  page: number
  categories: CatalogCategory[]
  priceBounds: PriceBounds
  activeCategorySlugs: string[]
  activeMinPrice: number | null
  activeMaxPrice: number | null
  activeMinRating: number | null
  activeInStockOnly: boolean
  activeSort: ProductCatalogSort
}

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

// Presentational + navigation only — all data (products, category counts,
// price bounds, pagination totals) is fetched server-side by
// products/page.tsx via the real, unstable_cache-wrapped
// getProductCatalog.ts queries (see DATA_FETCHING_PATTERN.md). Every
// filter/sort/page change just navigates to a new `/products?...` URL —
// same shape as BlogContent.tsx's search-param-driven listing — so there is
// no client-side array filtering anywhere in this component.
export default function ProductsPageClient({
  products,
  total,
  totalPages,
  page,
  categories,
  priceBounds,
  activeCategorySlugs,
  activeMinPrice,
  activeMaxPrice,
  activeMinRating,
  activeInStockOnly,
  activeSort,
}: ProductsPageClientProps) {
  const t = useTranslations('ProductsPage')
  const router = useRouter()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)

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

  const navigate = (overrides: Partial<QueryState>) => {
    const next: QueryState = {
      category: activeCategorySlugs,
      minPrice: activeMinPrice,
      maxPrice: activeMaxPrice,
      rating: activeMinRating,
      inStock: activeInStockOnly,
      sort: activeSort,
      page: 1,
      ...overrides,
    }

    const query: Record<string, string> = {}
    if (next.category.length > 0) query.category = next.category.join(',')
    if (next.minPrice !== null && next.minPrice !== priceBounds.min) query.minPrice = String(next.minPrice)
    if (next.maxPrice !== null && next.maxPrice !== priceBounds.max) query.maxPrice = String(next.maxPrice)
    if (next.rating !== null) query.rating = String(next.rating)
    if (next.inStock) query.inStock = '1'
    if (next.sort !== 'newest') query.sort = next.sort
    if (next.page > 1) query.page = String(next.page)

    router.push({ pathname: '/products', query })
  }

  const toggleCategory = (slug: string) => {
    const nextCategories = activeCategorySlugs.includes(slug)
      ? activeCategorySlugs.filter((c) => c !== slug)
      : [...activeCategorySlugs, slug]
    navigate({ category: nextCategories })
  }

  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') },
  ]

  const activeFiltersList: FilterBadge[] = [
    ...activeCategorySlugs.map((slug) => {
      const category = categories.find((c) => c.slug === slug)
      return { id: `cat-${slug}`, label: category?.name ?? slug, type: 'category', value: slug }
    }),
    ...(activeMinPrice !== null ? [{ id: 'price-min', label: `Min: ${formatAmount(activeMinPrice)}`, type: 'priceMin' }] : []),
    ...(activeMaxPrice !== null ? [{ id: 'price-max', label: `Max: ${formatAmount(activeMaxPrice)}`, type: 'priceMax' }] : []),
    ...(activeMinRating !== null ? [{ id: 'rating', label: `${activeMinRating}+ Stars`, type: 'rating' }] : []),
    ...(activeInStockOnly ? [{ id: 'stock', label: t('inStockOnly'), type: 'inStock' }] : []),
  ]

  const removeFilter = (id: string, type: string, value?: string) => {
    switch (type) {
      case 'category':
        navigate({ category: activeCategorySlugs.filter((c) => c !== value) })
        break
      case 'priceMin':
        navigate({ minPrice: null })
        break
      case 'priceMax':
        navigate({ maxPrice: null })
        break
      case 'rating':
        navigate({ rating: null })
        break
      case 'inStock':
        navigate({ inStock: false })
        break
    }
  }

  const clearAllFilters = () => {
    router.push({ pathname: '/products', query: {} })
  }

  const filterSections: FilterSection[] = [
    {
      id: 'categories',
      title: t('filterCategories'),
      defaultExpanded: true,
      content: (
        <div className="space-y-2">
          {categories.map((category) => (
            <label key={category.slug} className="flex items-center justify-between cursor-pointer">
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={activeCategorySlugs.includes(category.slug)}
                  onChange={() => toggleCategory(category.slug)}
                  className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
                />
                <span className="text-sm text-dark">{category.name}</span>
              </div>
              <span className="text-xs text-gray-custom">{category.productCount}</span>
            </label>
          ))}
        </div>
      ),
    },
    {
      id: 'price',
      title: t('filterPrice'),
      defaultExpanded: true,
      content: (
        <PriceRangeFilter
          min={priceBounds.min}
          max={priceBounds.max}
          step={priceStep}
          values={[minPrice, maxPrice]}
          onChange={([newMin, newMax]) => navigate({ minPrice: newMin, maxPrice: newMax })}
        />
      ),
    },
    {
      id: 'rating',
      title: t('filterRating'),
      defaultExpanded: true,
      content: <RatingFilter value={activeMinRating} onChange={(rating) => navigate({ 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={activeInStockOnly}
              onChange={(e) => navigate({ 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 ${activeInStockOnly ? 'translate-x-5' : ''}`}
            />
          </div>
        </label>
      ),
    },
  ]

  return (
    <Container className="mt-4">
      <OtherHeader
        title={t('headerTitle')}
        subtitle={t('headerSubtitle')}
        description={t('headerDescription')}
        badgeText={t('headerBadge')}
        totalProducts={total}
      />

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

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

          <SortDropdown
            options={sortOptions}
            value={activeSort}
            onChange={(value) => navigate({ 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">
              {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}
                />
              ))}
            </div>
          )}

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