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

import { useCallback, useEffect, useRef } from 'react';
import { useAppSelector, useAppDispatch } from '@/redux/hooks';
import { ClosedRequestsFilters } from '../types/closedRequests.types';
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/closedRequestsSlice';

interface UseClosedRequestsFiltersOptions {
  onFiltersChange?: (filters: ClosedRequestsFilters) => void;
  debounceMs?: number;
}

export function useClosedRequestsFilters({ onFiltersChange, debounceMs = 500 }: UseClosedRequestsFiltersOptions = {}) {
  const dispatch = useAppDispatch();
  const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isInitialMount = useRef(true);
  
  const { searchTerm, statusFilter, priorityFilter, templateTypeFilter, form16FinancialYear, form16Quarter, sortBy, sortOrder, currentPage } = useAppSelector((state) => state.closedRequests);
  
  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') => dispatch(setSortByAction(value)), [dispatch]);
  const setSortOrder = useCallback((value: 'asc' | 'desc') => dispatch(setSortOrderAction(value)), [dispatch]);
  const setCurrentPage = useCallback((value: number) => dispatch(setCurrentPageAction(value)), [dispatch]);

  const getFilters = useCallback((): ClosedRequestsFilters => {
    return {
      search: searchTerm,
      status: statusFilter,
      priority: priorityFilter,
      templateType: templateTypeFilter !== 'all' ? templateTypeFilter : undefined,
      financialYear: templateTypeFilter === 'FORM_16' && form16FinancialYear ? form16FinancialYear : undefined,
      quarter: templateTypeFilter === 'FORM_16' && form16Quarter ? form16Quarter : undefined,
      sortBy,
      sortOrder,
    };
  }, [searchTerm, statusFilter, priorityFilter, templateTypeFilter, form16FinancialYear, form16Quarter, sortBy, sortOrder]);

  // Debounced filter change handler
  useEffect(() => {
    // Skip initial mount to prevent double fetch
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }

    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
    }

    const timeoutId = setTimeout(() => {
      if (onFiltersChange) {
        onFiltersChange(getFilters());
      }
    }, searchTerm ? debounceMs : 0); // Debounce only for search, instant for dropdowns

    debounceTimeoutRef.current = timeoutId;

    return () => {
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
      }
    };
  }, [searchTerm, statusFilter, priorityFilter, templateTypeFilter, form16FinancialYear, form16Quarter, sortBy, sortOrder, onFiltersChange, getFilters, debounceMs]);

  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,
    priorityFilter,
    statusFilter,
    templateTypeFilter,
    form16FinancialYear,
    form16Quarter,
    sortBy,
    sortOrder,
    currentPage,
    setSearchTerm,
    setPriorityFilter,
    setStatusFilter,
    setTemplateTypeFilter,
    setForm16FinancialYear,
    setForm16Quarter,
    setSortBy,
    setSortOrder,
    setCurrentPage,
    clearFilters,
    activeFiltersCount,
    getFilters,
  };
}

