'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import ProductCard from '@/components/product/ProductCard';
import ShopFilters from '@/components/shop/ShopFilters';
import { Category, SortOption } from '@/domain/entities';
import { FilterProductsUseCase } from '@/application/use-cases/catalog/FilterProducts';
import { useCatalogFilter } from '@/presentation/hooks/useCatalog';
import { useTranslation } from '@/hooks/useTranslation';

export default function ShopPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useTranslation();

  const [selectedCategory, setSelectedCategory] = useState<Category | 'all'>(
    FilterProductsUseCase.parseCategory(searchParams.get('category'))
  );
  const [sortBy, setSortBy] = useState<SortOption>('featured');
  const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '');

  useEffect(() => {
    setSelectedCategory(
      FilterProductsUseCase.parseCategory(searchParams.get('category'))
    );
    setSearchQuery(searchParams.get('q') || '');
  }, [searchParams]);

  const pushParams = useCallback(
    (updates: { category?: Category | 'all'; q?: string }) => {
      const params = new URLSearchParams(searchParams.toString());

      if (updates.category !== undefined) {
        if (updates.category === 'all') params.delete('category');
        else params.set('category', updates.category);
      }

      if (updates.q !== undefined) {
        if (updates.q) params.set('q', updates.q);
        else params.delete('q');
      }

      const qs = params.toString();
      router.push(qs ? `/shop?${qs}` : '/shop', { scroll: false });
    },
    [router, searchParams]
  );

  const handleCategoryChange = (category: Category | 'all') => {
    setSelectedCategory(category);
    pushParams({ category });
  };

  const handleSearchChange = (query: string) => {
    setSearchQuery(query);
    pushParams({ q: query });
  };

  const filteredProducts = useCatalogFilter({
    category: selectedCategory,
    searchQuery,
    sortBy,
  });

  return (
    <div className="bg-gray-50">
      <div className="border-b border-gray-100 bg-white">
        <div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
          <h1 className="section-heading mb-2">{t('shop.title')}</h1>
          <p className="text-gray-500">{t('shop.subtitle')}</p>
        </div>
      </div>

      <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
        <div className="flex flex-col gap-8 lg:flex-row">
          <aside className="lg:w-64 lg:shrink-0">
            <div className="card-premium sticky top-24 p-6">
              <ShopFilters
                selectedCategory={selectedCategory}
                onCategoryChange={handleCategoryChange}
                sortBy={sortBy}
                onSortChange={setSortBy}
                searchQuery={searchQuery}
                onSearchChange={handleSearchChange}
                totalResults={filteredProducts.length}
              />
            </div>
          </aside>

          <div className="flex-1">
            {filteredProducts.length === 0 ? (
              <div className="card-premium flex flex-col items-center justify-center p-16 text-center">
                <p className="mb-2 text-lg font-semibold text-brand-900">
                  {t('shop.noProducts')}
                </p>
                <p className="text-sm text-gray-500">{t('shop.noProductsHint')}</p>
              </div>
            ) : (
              <div className="grid gap-6 sm:grid-cols-2 xl:grid-cols-3">
                {filteredProducts.map((product) => (
                  <ProductCard key={product.id} product={product} />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}