import { Product } from "lib/shopify/types";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { filterAndSortProducts, filterUtils } from "../utils/productHelpers";

/**
 * Custom hook for managing product filtering and sorting state
 */
export function useProductFilters(products: Product[]) {
  const [activeFilters, setActiveFilters] = useState<string[]>([]);
  const [sortOption, setSortOption] = useState('default');
  const searchParams = useSearchParams();
  
  // Load filters from URL on initial render
  useEffect(() => {
    const newActiveFilters = filterUtils.getFiltersFromUrl(searchParams as URLSearchParams);
    const sort = searchParams.get('sort');
    
    // Set active filters if there are any
    if (newActiveFilters.length > 0) {
      setActiveFilters(newActiveFilters);
    }
    
    if (sort) {
      setSortOption(sort);
    }
  }, [searchParams]);
  
  const handleApplyFilters = (filters: string[]) => {
    setActiveFilters(filters);
    filterUtils.updateUrlParams(filters, sortOption);
  };

  const handleSortChange = (newSortOption: string) => {
    setSortOption(newSortOption);
    filterUtils.updateUrlParams(activeFilters, newSortOption);
  };
  
  const removeFilter = (filter: string) => {
    let newFilters: string[];
    
    if (filter.startsWith('Cijena:')) {
      newFilters = activeFilters.filter(f => !f.startsWith('Cijena:'));
    } else {
      newFilters = activeFilters.filter(f => f !== filter);
    }
    
    setActiveFilters(newFilters);
    filterUtils.updateUrlParams(newFilters, sortOption);
  };
  
  const clearAllFilters = () => {
    setActiveFilters([]);
    filterUtils.updateUrlParams([], sortOption);
  };
  
  const sortedProducts = filterAndSortProducts(products, activeFilters, sortOption);
  
  return {
    activeFilters,
    sortOption,
    sortedProducts,
    handleApplyFilters,
    handleSortChange,
    removeFilter,
    clearAllFilters,
    formatFilterTag: filterUtils.formatFilterTag
  };
} 