import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import CloseIcon from "../icons/close.svg"; const Filter = ({ isActive, closeFilter, defaultRoute, defaultPriceFrom, defaultPriceTo, defaultCategory, defaultBrand, defaultOrderBy, searchResults, disableFilter = [] }) => { const router = useRouter(); const [priceFrom, setPriceFrom] = useState(defaultPriceFrom); const [priceTo, setPriceTo] = useState(defaultPriceTo); const [orderBy, setOrderBy] = useState(defaultOrderBy); const [selectedCategory, setSelectedCategory] = useState(defaultCategory); const [selectedBrand, setSelectedBrand] = useState(defaultBrand); const [categories, setCategories] = useState([]); const [brands, setBrands] = useState([]); const filterRoute = () => { let filterRoute = []; let filterRoutePrefix = '?'; if (selectedBrand) filterRoute.push(`brand=${selectedBrand}`); if (selectedCategory) filterRoute.push(`category=${selectedCategory}`); if (priceFrom) filterRoute.push(`price_from=${priceFrom}`); if (priceTo) filterRoute.push(`price_to=${priceTo}`); if (orderBy) filterRoute.push(`order_by=${orderBy}`); if (defaultRoute.includes('?')) filterRoutePrefix = '&'; if (filterRoute.length > 0) { filterRoute = filterRoutePrefix + filterRoute.join('&'); } else { filterRoute = ''; } return defaultRoute + filterRoute; } useEffect(() => { const filterCategory = searchResults.facet_counts.facet_fields.category_name_str.filter((category, index) => { if (index % 2 == 0) { const productCountInCategory = searchResults.facet_counts.facet_fields.category_name_str[index + 1]; if (productCountInCategory > 0) return category; } }); setCategories(filterCategory); const filterBrand = searchResults.facet_counts.facet_fields.brand_str.filter((brand, index) => { if (index % 2 == 0) { const productCountInBrand = searchResults.facet_counts.facet_fields.brand_str[index + 1]; if (productCountInBrand > 0) return brand; } }); setBrands(filterBrand); }, [searchResults]); const submit = (e) => { e.preventDefault(); closeFilter(); router.push(filterRoute(), undefined, { scroll: false }); } const reset = () => { setSelectedBrand(''); setSelectedCategory(''); setPriceFrom(''); setPriceTo(''); setOrderBy(''); } const changeOrderBy = (value) => { if (orderBy == value) { setOrderBy(''); } else { setOrderBy(value); } } return (