import * as React from "react";
import {
  cleanFilterParams,
  FilterValue,
} from "@/shared/utils/filterParams";

export const useCombinedFilters = <TFilters extends object = Record<string, FilterValue>>(
  initialFilters = {} as TFilters,
) => {
  const [filters, setFilters] = React.useState<Partial<TFilters>>(
    cleanFilterParams(initialFilters),
  );

  const setFilter = React.useCallback(
    (key: keyof TFilters, value: FilterValue) => {
      setFilters((prev) =>
        cleanFilterParams({
          ...prev,
          [key]: value,
        } as TFilters),
      );
    },
    [],
  );

  const setManyFilters = React.useCallback((nextFilters: Partial<TFilters>) => {
    setFilters((prev) =>
      cleanFilterParams({
        ...prev,
        ...nextFilters,
      } as TFilters),
    );
  }, []);

  const removeFilter = React.useCallback((key: keyof TFilters) => {
    setFilters((prev) => {
      const next = { ...prev };
      delete next[key];
      return cleanFilterParams(next as TFilters);
    });
  }, []);

  const removeManyFilters = React.useCallback((keys: Array<keyof TFilters>) => {
    setFilters((prev) => {
      const next = { ...prev };
      keys.forEach((key) => delete next[key]);
      return cleanFilterParams(next as TFilters);
    });
  }, []);

  const clearFilters = React.useCallback(() => {
    setFilters({});
  }, []);

  return {
    filters,
    setFilter,
    setFilters: setManyFilters,
    removeFilter,
    removeFilters: removeManyFilters,
    clearFilters,
  };
};
