import { useCallback, useState } from 'react';
import { AbsenceFilters } from '@/shared/api/endpoints/hr/absence/absence';

const statusMap: Record<string, string> = {
  'en cours': 'In_progress',
  'non traité': 'Unprocessed',
  'non traite': 'Unprocessed',
  'traité': 'Treated',
  'traite': 'Treated',
  'refusé': 'Rejected',
  'refuse': 'Rejected',
  'validé': 'Approved',
  'valide': 'Approved',
  'en attente': 'Waiting'
};

type FilterType = Record<string, { value: string; condition: string }>;

export const useAbsenceFilters = () => {
  const [nonTraitedFilters, setNonTraitedFilters] = useState<FilterType>({});
  const [traitedFilters, setTraitedFilters] = useState<FilterType>({});

  const buildApiFilters = useCallback((
    paginationParams: { page: number; size: number },
    isTraited: boolean
  ): AbsenceFilters => {
    // Start with only pagination - no requestType filter to show both ABSENCE and LEAVE
    const apiFilters: AbsenceFilters = {
      ...paginationParams
    };

    const currentFilters = isTraited ? traitedFilters : nonTraitedFilters;

    // If no filters, return only required params
    if (Object.keys(currentFilters).length === 0) {
      return apiFilters;
    }

    Object.entries(currentFilters).forEach(([key, filter]) => {
      // Skip empty values
      if (!filter?.value || filter.value.trim() === '') return;

      const value = filter.value.trim();

      switch (key) {
        case 'numeroEnregistrement':
          // Support both ABS-XXXX and CONG-XXXX formats
          const match = value.match(/(?:ABS|CONG)-0*(\d+)/i);
          if (match && match[1]) {
            const numericId = parseInt(match[1], 10);
            if (!isNaN(numericId)) {
              apiFilters.id = numericId;
              delete apiFilters.absenceNumber;
            }
          }
          break;

        case 'nomChauffeur':
          const nameParts = value.split(' ');
          apiFilters.firstName = nameParts[0];
          if (nameParts.length > 1) {
            apiFilters.lastName = nameParts.slice(1).join(' ');
          }
          break;

        case 'statut':
          const normalizedStatus = value.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
          const matchedStatus = Object.entries(statusMap).find(
            ([french]) => normalizedStatus.includes(french.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""))
          );
          if (matchedStatus) {
            apiFilters.states = matchedStatus[1];
          }
          break;

        case 'dateDebut':
          const startDate = new Date(value);
          if (!isNaN(startDate.getTime())) {
            apiFilters.startDateFrom = startDate.toISOString().split('T')[0];
          }
          break;

        case 'dateFin':
          const endDate = new Date(value);
          if (!isNaN(endDate.getTime())) {
            apiFilters.endDateTo = endDate.toISOString().split('T')[0];
          }
          break;

        case 'type':
          apiFilters.functionType = value.toLowerCase() === 'chauffeur' ? 'DRIVER' : 'SEDENTARY';
          break;

        case 'affecteTrajet':
          apiFilters.affectedToTrip = value.toLowerCase() === 'oui' || value.toLowerCase() === 'true';
          break;

        // Map other fields directly
        case 'typeAbsenceLabel':
          apiFilters.absenceType = value;
          break;
        case 'autorisePar':
          apiFilters.authorizedBy = value;
          break;
        case 'validerPar':
          apiFilters.validatedBy = value;
          break;
        case 'departement':
          apiFilters.department = value;
          break;
        case 'modeReception':
          apiFilters.receivingMethod = value;
          break;
      }
    });

    return apiFilters;
  }, [traitedFilters, nonTraitedFilters]);

  const handleFilterChange = useCallback((key: string, value: string | null, condition: string, isTraited: boolean) => {
    const setFilters = isTraited ? setTraitedFilters : setNonTraitedFilters;
    
    setFilters(prev => {
      const newFilters = { ...prev };
      
      // Remove filter if value is empty, null, or only whitespace
      if (!value || value.trim() === '') {
        delete newFilters[key];
        return newFilters;
      }
      
      // Add/update filter
      newFilters[key] = { value, condition };
      return newFilters;
    });
  }, []);

  const resetFilters = useCallback((isTraited: boolean) => {
    if (isTraited) {
      setTraitedFilters({});
    } else {
      setNonTraitedFilters({});
    }
  }, []);

  const resetAllFilters = useCallback(() => {
    setTraitedFilters({});
    setNonTraitedFilters({});
  }, []);

  return {
    traitedFilters,
    nonTraitedFilters,
    buildApiFilters,
    handleFilterChange,
    resetFilters,
    resetAllFilters
  };
}; 