/**
 * Hook for managing Requests filters using Redux
 * Filters persist in Redux (in-memory) during navigation, but reset on page refresh
 */

import { useCallback } from 'react';
import { useAppSelector, useAppDispatch } from '@/redux/hooks';
import type { DateRange } from '@/services/dashboard.service';
import type { RequestFilters } from '../types/requests.types';
import type { RequestTypeFilter } from '../redux/requestsSlice';
import {
  setSearchTerm as setSearchTermAction,
  setStatusFilter as setStatusFilterAction,
  setPriorityFilter as setPriorityFilterAction,
  setTemplateTypeFilter as setTemplateTypeFilterAction,
  setRequestTypeFilter as setRequestTypeFilterAction,
  setForm16FinancialYear as setForm16FinancialYearAction,
  setForm16Quarter as setForm16QuarterAction,
  setSlaComplianceFilter as setSlaComplianceFilterAction,
  setDepartmentFilter as setDepartmentFilterAction,
  setInitiatorFilter as setInitiatorFilterAction,
  setApproverFilter as setApproverFilterAction,
  setApproverFilterType as setApproverFilterTypeAction,
  setDateRange as setDateRangeAction,
  setCustomStartDate as setCustomStartDateAction,
  setCustomEndDate as setCustomEndDateAction,
  setShowCustomDatePicker as setShowCustomDatePickerAction,
  setCurrentPage as setCurrentPageAction,
  clearFilters as clearFiltersAction,
} from '../redux/requestsSlice';

export function useRequestsFilters() {
  const dispatch = useAppDispatch();

  // Get all filter state from Redux
  const {
    searchTerm,
    statusFilter,
    priorityFilter,
    templateTypeFilter,
    requestTypeFilter,
    form16FinancialYear,
    form16Quarter,
    slaComplianceFilter,
    departmentFilter,
    initiatorFilter,
    approverFilter,
    approverFilterType,
    dateRange,
    customStartDate,
    customEndDate,
    showCustomDatePicker,
    currentPage,
  } = useAppSelector((state) => state.requests);

  // Create setters that dispatch Redux actions
  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 setRequestTypeFilter = useCallback((value: RequestTypeFilter) => dispatch(setRequestTypeFilterAction(value)), [dispatch]);
  const setForm16FinancialYear = useCallback((value: string) => dispatch(setForm16FinancialYearAction(value)), [dispatch]);
  const setForm16Quarter = useCallback((value: string) => dispatch(setForm16QuarterAction(value)), [dispatch]);
  const setSlaComplianceFilter = useCallback((value: string) => dispatch(setSlaComplianceFilterAction(value)), [dispatch]);
  const setDepartmentFilter = useCallback((value: string) => dispatch(setDepartmentFilterAction(value)), [dispatch]);
  const setInitiatorFilter = useCallback((value: string) => dispatch(setInitiatorFilterAction(value)), [dispatch]);
  const setApproverFilter = useCallback((value: string) => dispatch(setApproverFilterAction(value)), [dispatch]);
  const setApproverFilterType = useCallback((value: 'current' | 'any') => dispatch(setApproverFilterTypeAction(value)), [dispatch]);
  const setDateRange = useCallback((value: DateRange) => dispatch(setDateRangeAction(value)), [dispatch]);
  const setCustomStartDate = useCallback((value: Date | undefined) => dispatch(setCustomStartDateAction(value)), [dispatch]);
  const setCustomEndDate = useCallback((value: Date | undefined) => dispatch(setCustomEndDateAction(value)), [dispatch]);
  const setShowCustomDatePicker = useCallback((value: boolean) => dispatch(setShowCustomDatePickerAction(value)), [dispatch]);
  const setCurrentPage = useCallback((value: number) => dispatch(setCurrentPageAction(value)), [dispatch]);

  const getFilters = useCallback((): RequestFilters => {
    const isForm16 = templateTypeFilter === 'FORM_16';
    if (isForm16) {
      return {
        templateType: 'FORM_16',
        financialYear: form16FinancialYear !== 'all' ? form16FinancialYear : undefined,
        quarter: form16Quarter !== 'all' ? form16Quarter : undefined,
      };
    }
    return {
      search: searchTerm || undefined,
      status: statusFilter !== 'all' ? statusFilter : undefined,
      priority: priorityFilter !== 'all' ? priorityFilter : undefined,
      templateType: templateTypeFilter !== 'all' ? templateTypeFilter : undefined,
      slaCompliance: slaComplianceFilter !== 'all' ? slaComplianceFilter : undefined,
      department: departmentFilter !== 'all' ? departmentFilter : undefined,
      initiator: initiatorFilter !== 'all' ? initiatorFilter : undefined,
      approver: approverFilter !== 'all' ? approverFilter : undefined,
      approverType: approverFilter !== 'all' ? approverFilterType : undefined,
      dateRange,
      startDate: customStartDate,
      endDate: customEndDate
    };
  }, [
    searchTerm,
    statusFilter,
    priorityFilter,
    templateTypeFilter,
    form16FinancialYear,
    form16Quarter,
    slaComplianceFilter,
    departmentFilter,
    initiatorFilter,
    approverFilter,
    approverFilterType,
    dateRange,
    customStartDate,
    customEndDate
  ]);

  const clearFilters = useCallback(() => {
    dispatch(clearFiltersAction());
  }, [dispatch]);

  const handleDateRangeChange = useCallback((value: string) => {
    const newRange = value as DateRange;
    dispatch(setDateRangeAction(newRange));
    if (newRange !== 'custom') {
      dispatch(setCustomStartDateAction(undefined));
      dispatch(setCustomEndDateAction(undefined));
      dispatch(setShowCustomDatePickerAction(false));
    } else {
      dispatch(setShowCustomDatePickerAction(true));
    }
  }, [dispatch]);

  const handleApplyCustomDate = useCallback(() => {
    if (customStartDate && customEndDate) {
      if (customStartDate > customEndDate) {
        // Swap dates if start is after end
        dispatch(setCustomStartDateAction(customEndDate));
        dispatch(setCustomEndDateAction(customStartDate));
      }
      dispatch(setShowCustomDatePickerAction(false));
    }
  }, [customStartDate, customEndDate, dispatch]);

  const isForm16 = templateTypeFilter === 'FORM_16';
  const hasActiveFilters: boolean = isForm16
    ? !!(templateTypeFilter === 'FORM_16' && (form16FinancialYear !== 'all' || form16Quarter !== 'all'))
    : !!(
        searchTerm ||
        statusFilter !== 'all' ||
        priorityFilter !== 'all' ||
        templateTypeFilter !== 'all' ||
        requestTypeFilter !== 'all' ||
        ((requestTypeFilter as RequestTypeFilter) === 'form_16' && (form16FinancialYear !== 'all' || form16Quarter !== 'all')) ||
        slaComplianceFilter !== 'all' ||
        departmentFilter !== 'all' ||
        initiatorFilter !== 'all' ||
        approverFilter !== 'all' ||
        dateRange !== 'all' ||
        customStartDate ||
        customEndDate
      );

  return {
    // State
    searchTerm,
    statusFilter,
    priorityFilter,
    templateTypeFilter,
    requestTypeFilter,
    form16FinancialYear,
    form16Quarter,
    isForm16,
    slaComplianceFilter,
    departmentFilter,
    initiatorFilter,
    approverFilter,
    approverFilterType,
    dateRange,
    customStartDate,
    customEndDate,
    showCustomDatePicker,
    currentPage,
    hasActiveFilters,
    // Setters
    setSearchTerm,
    setStatusFilter,
    setPriorityFilter,
    setTemplateTypeFilter,
    setRequestTypeFilter,
    setForm16FinancialYear,
    setForm16Quarter,
    setSlaComplianceFilter,
    setDepartmentFilter,
    setInitiatorFilter,
    setApproverFilter,
    setApproverFilterType,
    setDateRange,
    setCustomStartDate,
    setCustomEndDate,
    setShowCustomDatePicker,
    setCurrentPage,
    // Helpers
    getFilters,
    clearFilters,
    handleDateRangeChange,
    handleApplyCustomDate
  };
}

