'use client'

import Image from 'next/image'
import { useEffect } from 'react'
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 { useLocaleAlternatesStore } from '@/store/localeAlternatesStore'
import { useCurrencyStore } from '@/store/currencyStore'
import type { CatalogProduct, PriceBounds, ProductCatalogSort } from '@/lib/db/queries/getProductCatalog'
import type { CategoryDetail } from '@/lib/db/queries/getCategoryDetail'

interface CategoryPageClientProps {
  category: CategoryDetail
  products: CatalogProduct[]
  total: number
  totalPages: number
  page: number
  priceBounds: PriceBounds
  activeMinPrice: number | null
  activeMaxPrice: number | null
  activeMinRating: number | null
  activeInStockOnly: boolean
  activeSort: ProductCatalogSort
  // locale code -> this category's URL in that language (slugs differ per
  // language). Registered with the language switcher — see localeAlternatesStore.ts.
  alternatePaths: Record<string, string>
  defaultLocale: string
}

type QueryState = {
  minPrice: number | null
  maxPrice: number | null
  rating: number | null
  inStock: boolean
  sort: ProductCatalogSort
  page: number
}

function stripHtml(html: string): string {
  return html.replace(/<[^>]+>/g, '').trim()
}

// Presentational + navigation only — real category info and the real
// filtered/sorted/paginated product list are both fetched server-side by
// category/[slug]/page.tsx (see DATA_FETCHING_PATTERN.md and
// ProductsPageClient.tsx, the identical pattern for the full catalog page).
// Every filter/sort/page change navigates to a new `/category/[slug]?...`
// URL — no client-side array filtering.
export default function CategoryPageClient({
  category,
  products,
  total,
  totalPages,
  page,
  priceBounds,
  activeMinPrice,
  activeMaxPrice,
  activeMinRating,
  activeInStockOnly,
  activeSort,
  alternatePaths,
  defaultLocale,
}: CategoryPageClientProps) {
  const t = useTranslations('ProductsPage')
  const router = useRouter()
  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 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 = {
      minPrice: activeMinPrice,
      maxPrice: activeMaxPrice,
      rating: activeMinRating,
      inStock: activeInStockOnly,
      sort: activeSort,
      page: 1,
      ...overrides,
    }

    const query: Record<string, string> = {}
    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: `/category/${category.slug}`, query })
  }

  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[] = [
    ...(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) => {
    switch (type) {
      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: `/category/${category.slug}`, query: {} })
  }

  const filterSections: FilterSection[] = [
    {
      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>
      ),
    },
  ]

  const headerDescription = category.description ? stripHtml(category.description) : undefined
  const headerIcon = category.iconUrl ? (
    <Image src={category.iconUrl} alt={category.altText || category.name} width={20} height={20} className="rounded object-cover" />
  ) : undefined

  return (
    <Container className="mt-4">
      <OtherHeader
        title={category.name}
        description={headerDescription}
        icon={headerIcon}
        badgeText={category.name}
        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>
  )
}
