"use client";

import { useState } from "react";
import {
  EMPTY_OPPORTUNITY_FILTERS,
  type AllOpportunitiesFiltersData,
} from "./opportunityFilters";

/**
 * The filter state every opportunity list keeps, and the four pieces that have
 * to move together: the applied filters, the remount key that resets the form,
 * and whether Apply / Clear are enabled.
 *
 * `clearFiltersKey` is a remount rather than a reset call because the form is
 * Formik's and is seeded from `initialValues`; bumping the key is what makes a
 * clear visible in the fields as well as in the results.
 */
export function useOpportunityFilters(
  initial?: Partial<AllOpportunitiesFiltersData>
) {
  const [filters, setFilters] = useState<AllOpportunitiesFiltersData>({
    ...EMPTY_OPPORTUNITY_FILTERS(),
    ...initial,
  });
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const [isFilterEmpty, setIsFilterEmpty] = useState(true);

  return {
    filters,
    setFilters,
    clearFiltersKey,
    isFilterDirty,
    setIsFilterDirty,
    isFilterEmpty,
    setIsFilterEmpty,
    clearFilters: () => {
      setFilters(EMPTY_OPPORTUNITY_FILTERS());
      setClearFiltersKey((prev) => prev + 1);
    },
  };
}
