import { useEffect, useMemo } from "react";
import useCategoryFilter from "./useCategoryFilter";
import useLocationsFilter from "./useLocationsFilter";
import useSubcategoryFilter from "./useSubcategoryFilter";

const useFilters = (clearAll = false) => {
  const category = useCategoryFilter();
  const subcategory = useSubcategoryFilter();
  const locations = useLocationsFilter();

  useEffect(() => {
    if (clearAll) {
      clear();
    }
  }, []);

  const numOfFiltersChosen = useMemo(() => {
    let sumOfFiltersChosen = 0;
    if (category.selectedCategoryLocally?._id) sumOfFiltersChosen++;
    if (subcategory.selectedSubcategoryLocally?._id) sumOfFiltersChosen++;
    sumOfFiltersChosen += locations.selectedLocationsLocally.length;
    return sumOfFiltersChosen;
  }, [
    category.selectedCategoryLocally,
    subcategory.selectedSubcategoryLocally,
    locations.selectedLocationsLocally,
  ]);

  const apply = () => {
    category.apply();
    subcategory.apply();
    locations.apply();
  };

  const clear = () => {
    category.clear();
    subcategory.clear();
    locations.clear();
  };

  return {
    category,
    subcategory,
    locations,
    numOfFiltersChosen,
    apply,
    clear,
  };
};
export default useFilters;
