'use client';

import { Product } from "lib/shopify/types";
import { useState } from "react";
import { Heading } from "../ui/Typography";
import { FilterSidebar } from "./FilterSidebar";
import { FilterButton } from "./ProductComponents/FilterButton";
import { FilterTagList } from "./ProductComponents/FilterTagList";
import { ProductCounter } from "./ProductComponents/ProductCounter";
import { ProductsList } from "./ProductComponents/ProductsList";
import { SortDropdown } from "./client/SortDropdown";
import { useProductFilters } from "./hooks/useProductFilters";

interface ProductGridProps {
  products: Product[];
  title?: string;
  showControls?: boolean;
}

export function ProductGrid({ products, title = "Gotovi proizvodi", showControls = true }: ProductGridProps) {
  const [isSidebarOpen, setSidebarOpen] = useState(false);
  const { 
    activeFilters, 
    sortOption, 
    sortedProducts, 
    handleApplyFilters, 
    handleSortChange, 
    removeFilter, 
    clearAllFilters, 
    formatFilterTag 
  } = useProductFilters(products);

  return (
    <div className="w-full">
      <div>
        {title && <Heading level={2} className="mb-8">{title}</Heading>}
        
        {/* Filter and Sort Controls */}
        {showControls && (
          <>
            <div className="flex justify-between items-center mb-4">
              <FilterButton onClick={() => setSidebarOpen(true)} />
              <SortDropdown 
                value={sortOption} 
                onChange={handleSortChange} 
              />
            </div>
            
            {/* Filter tags and product count */}
            <div className="flex justify-between items-center mb-8">
              <FilterTagList 
                filters={activeFilters} 
                formatTag={formatFilterTag} 
                onRemove={removeFilter} 
                onClearAll={clearAllFilters} 
              />
              <ProductCounter count={sortedProducts.length} />
            </div>
          </>
        )}
        
        {/* Products grid */}
        <ProductsList products={showControls ? sortedProducts : products} />
      </div>

      {/* Filter Sidebar */}
      {showControls && (
        <FilterSidebar
          isOpen={isSidebarOpen}
          onClose={() => setSidebarOpen(false)}
          onApplyFilters={handleApplyFilters}
          activeFilters={activeFilters}
        />
      )}
    </div>
  );
} 