import { useQueryStates } from 'nuqs';

import { KUDOS_FILTERS_STATE } from 'src/pages/dashboard/acknowledgements/constants';
import {
  type KudosRankingFiltersState,
  type KudosRankingFilterValues,
} from 'src/pages/dashboard/acknowledgements/types';
import {
  idsToRecord,
  recordToIds,
} from 'src/pages/dashboard/acknowledgements/utils';

export const useKudosRankingFilters = () => {
  const [filtersState, setFiltersState] = useQueryStates(KUDOS_FILTERS_STATE);

  const { startDate, endDate, categoryIds, segmentationItemIds } = filtersState;

  const appliedFilters: KudosRankingFiltersState = {
    startDate,
    endDate,
    categoryIds,
    segmentationItemIds,
  };

  const currentFormValues: KudosRankingFilterValues = {
    startDate: startDate ?? null,
    endDate: endDate ?? null,
    categories: idsToRecord(categoryIds),
    segmentationItemIds: idsToRecord(segmentationItemIds),
  };

  const setFilters = (values: KudosRankingFilterValues) => {
    const cats = recordToIds(values.categories);
    const segs = recordToIds(values.segmentationItemIds);
    setFiltersState({
      startDate: values.startDate,
      endDate: values.endDate,
      categoryIds: cats.length > 0 ? cats : null,
      segmentationItemIds: segs.length > 0 ? segs : null,
    });
  };

  const clearFilters = () => {
    setFiltersState({
      startDate: null,
      endDate: null,
      categoryIds: null,
      segmentationItemIds: null,
    });
  };

  const appliedFiltersCount = [
    startDate,
    endDate,
    categoryIds?.length ? categoryIds : null,
    segmentationItemIds?.length ? segmentationItemIds : null,
  ].filter(Boolean).length;

  return {
    appliedFilters,
    appliedFiltersCount,
    hasDateFilters: !!(startDate || endDate),
    currentFormValues,
    setFilters,
    clearFilters,
  };
};
