/**
 * Hook for managing Open Requests filters and sorting using Redux
 */

import { useCallback } from 'react';
import { useAppSelector, useAppDispatch } from '@/redux/hooks';
import {
  setSearchTerm as setSearchTermAction,
  setStatusFilter as setStatusFilterAction,
  setPriorityFilter as setPriorityFilterAction,
  setTemplateTypeFilter as setTemplateTypeFilterAction,
  setForm16FinancialYear as setForm16FinancialYearAction,
  setForm16Quarter as setForm16QuarterAction,
  setSortBy as setSortByAction,
  setSortOrder as setSortOrderAction,
  setCurrentPage as setCurrentPageAction,
  clearFilters as clearFiltersAction,
} from '../redux/openRequestsSlice';

export function useOpenRequestsFilters() {
  const dispatch = useAppDispatch();
  
  const { searchTerm, statusFilter, priorityFilter, templateTypeFilter, form16FinancialYear, form16Quarter, sortBy, sortOrder, currentPage } = useAppSelector((state) => state.openRequests);
  
  const setSearchTerm = useCallback((value: string) => dispatch(setSearchTermAction(value)), [dispatch]);
  const setStatusFilter = useCallback((value: string) => dispatch(setStatusFilterAction(value)), [dispatch]);
  const setPriorityFilter = useCallback((value: string) => dispatch(setPriorityFilterAction(value)), [dispatch]);
  const setTemplateTypeFilter = useCallback((value: string) => dispatch(setTemplateTypeFilterAction(value)), [dispatch]);
  const setForm16FinancialYear = useCallback((value: string) => dispatch(setForm16FinancialYearAction(value)), [dispatch]);
  const setForm16Quarter = useCallback((value: string) => dispatch(setForm16QuarterAction(value)), [dispatch]);
  const setSortBy = useCallback((value: 'created' | 'due' | 'priority' | 'sla') => dispatch(setSortByAction(value)), [dispatch]);
  const setSortOrder = useCallback((value: 'asc' | 'desc') => dispatch(setSortOrderAction(value)), [dispatch]);
  const setCurrentPage = useCallback((value: number) => dispatch(setCurrentPageAction(value)), [dispatch]);
  const clearFilters = useCallback(() => dispatch(clearFiltersAction()), [dispatch]);

  const activeFiltersCount = [
    searchTerm,
    priorityFilter !== 'all' ? priorityFilter : null,
    statusFilter !== 'all' ? statusFilter : null,
    templateTypeFilter !== 'all' ? templateTypeFilter : null,
    templateTypeFilter === 'FORM_16' && form16FinancialYear ? 'fy' : null,
    templateTypeFilter === 'FORM_16' && form16Quarter ? 'q' : null,
  ].filter(Boolean).length;

  return {
    searchTerm,
    statusFilter,
    priorityFilter,
    templateTypeFilter,
    form16FinancialYear,
    form16Quarter,
    sortBy,
    sortOrder,
    currentPage,
    setSearchTerm,
    setStatusFilter,
    setPriorityFilter,
    setTemplateTypeFilter,
    setForm16FinancialYear,
    setForm16Quarter,
    setSortBy,
    setSortOrder,
    setCurrentPage,
    clearFilters,
    activeFiltersCount,
  };
}

