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 => {
    const apiFilters: AbsenceFilters = {
      ...paginationParams,
      requestType: 'ABSENCE'
    };

    const currentFilters = isTraited ? traitedFilters : nonTraitedFilters;

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

      const value = filter.value.trim();

      switch (key) {
        case 'numeroEnregistrement':
          const match = value.match(/ABS-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, condition: string, isTraited: boolean) => {
    if (isTraited) {
      setTraitedFilters(prev => ({
        ...prev,
        [key]: { value, condition }
      }));
    } else {
      setNonTraitedFilters(prev => ({
        ...prev,
        [key]: { value, condition }
      }));
    }
  }, []);

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

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

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