import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { IRHAbsence } from '@/shared/types/absence-rh';
import { 
  calendarRhAbsenceEndpoints, 
  RhAbsenceCalendarDto, 
  CalendarStatisticsDto,
  CalendarFilters 
} from '@/shared/api/endpoints/hr/absence/calendarRhAbsence';

interface RHAbsenceCalendarState {
  // State
  loading: boolean;
  error: string | null;
  calendarAbsences: IRHAbsence[];
  selectedDateAbsences: IRHAbsence[];
  statistics: CalendarStatisticsDto | null;
  currentFilters: CalendarFilters;

  // Actions
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  setFilters: (filters: Partial<CalendarFilters>) => void;
  resetFilters: () => void;
  clearAbsences: () => void;

  // API Actions
  fetchAbsencesForCalendar: (filters: CalendarFilters) => Promise<IRHAbsence[]>;
  fetchAbsencesForDate: (date: string, statuses?: string[]) => Promise<IRHAbsence[]>;
  fetchAbsencesForMonth: (year: number, month: number, statuses?: string[]) => Promise<IRHAbsence[]>;
  fetchCalendarStatistics: (filters: CalendarFilters) => Promise<CalendarStatisticsDto>;
}

const INITIAL_FILTERS: CalendarFilters = {};

// Transform backend DTO to frontend interface
const transformToFrontendAbsence = (dto: RhAbsenceCalendarDto): IRHAbsence => {
  return {
    id: dto.id,
    absenceNumber: dto.absenceNumber,
    userId: dto.userId,
    user: {
      firstName: dto.firstName,
      lastName: dto.lastName,
      departmentName: dto.departmentName,
      functionType: dto.functionType
    },
    functionType: dto.functionType,
    absenceType: dto.absenceType,
    leaveType: dto.leaveType,
    requestType: dto.requestType,
    startDate: dto.startDate,
    endDate: dto.endDate,
    numberOfDays: dto.numberOfDays || 0,
    hoursCount: dto.hoursCount,
    state: dto.state,
    authorizedBy: dto.authorizedBy,
    validatedBy: dto.validatedBy,
    receivingMethod: dto.receivingMethod,
    affectedToTrip: dto.affectedToTrip,
    observations: dto.observations,
    rhComment: dto.rhComment,
    
    // Frontend compatibility fields
    numeroEnregistrement: dto.absenceNumber,
    nomChauffeur: dto.displayName || dto.userName || `${dto.firstName} ${dto.lastName}`,
    typeAbsence: dto.absenceType,
    typeAbsenceLabel: dto.absenceType,
    dateDebut: dto.startDate,
    dateFin: dto.endDate,
    statut: mapBackendStatusToFrontend(dto.status || dto.state),
    justificatif: dto.receivingMethod,
    modeReception: dto.receivingMethod,
    nbrHeures: dto.hoursCount,
    validerPar: dto.validatedBy,
    autorisePar: dto.authorizedBy,
    departement: dto.departmentName,
    type: dto.functionType?.toLowerCase() === 'driver' ? 'chauffeur' : 'sédentaire',
    affecteTrajet: dto.affectedToTrip,
    mode: 'view'
  };
};

// Map backend status to frontend status
const mapBackendStatusToFrontend = (backendStatus: string): string => {
  if (!backendStatus) return 'Non traité';
  
  switch (backendStatus.toLowerCase()) {
    case 'validated':
    case 'approved':
      return 'Validé';
    case 'rejected':
      return 'Refusé';
    case 'in_progress':
    case 'pending':
      return 'En cours';
    case 'untreated':
    case 'unprocessed':
    case 'non_traite':
      return 'Non traité';
    default:
      // If status doesn't match any known values, return as is but capitalized
      return backendStatus.charAt(0).toUpperCase() + backendStatus.slice(1).toLowerCase();
  }
};

export const useRHAbsenceCalendarStore = create<RHAbsenceCalendarState>()(
  devtools(
    (set, get) => ({
      // Initial state
      loading: false,
      error: null,
      calendarAbsences: [],
      selectedDateAbsences: [],
      statistics: null,
      currentFilters: INITIAL_FILTERS,

      // State actions
      setLoading: (loading: boolean) => set({ loading }),
      setError: (error: string | null) => set({ error }),
      setFilters: (filters: Partial<CalendarFilters>) =>
        set((state) => ({ currentFilters: { ...state.currentFilters, ...filters } })),
      resetFilters: () => set({ currentFilters: INITIAL_FILTERS }),
      clearAbsences: () => set({ calendarAbsences: [], selectedDateAbsences: [] }),

      // API actions
      fetchAbsencesForCalendar: async (filters: CalendarFilters) => {
        set({ loading: true, error: null });
        try {
          console.log('Store: fetchAbsencesForCalendar called with filters:', filters);
          
          // Update store filters state
          set((state) => ({ currentFilters: { ...state.currentFilters, ...filters } }));
          
          const response = await calendarRhAbsenceEndpoints.getAbsencesForCalendar(filters);
          console.log('Store: Calendar absences API response:', response.data);
          
          const transformedAbsences = response.data.map(transformToFrontendAbsence);
          set({
            calendarAbsences: transformedAbsences,
            loading: false,
          });
          
          return transformedAbsences;
        } catch (error: any) {
          console.error('Store: Calendar absences API error:', error);
          const errorMessage = error.response?.data?.message || error.message || 'Failed to fetch calendar absences';
          set({
            error: errorMessage,
            loading: false,
          });
          throw error;
        }
      },

      fetchAbsencesForDate: async (date: string, statuses?: string[]) => {
        set({ loading: true, error: null });
        try {
          console.log('Store: fetchAbsencesForDate called with date:', date, 'statuses:', statuses);
          
          const response = await calendarRhAbsenceEndpoints.getAbsencesForDate(date, statuses);
          console.log('Store: Date absences API response:', response.data);
          
          const transformedAbsences = response.data.map(transformToFrontendAbsence);
          set({
            selectedDateAbsences: transformedAbsences,
            loading: false,
          });
          
          return transformedAbsences;
        } catch (error: any) {
          console.error('Store: Date absences API error:', error);
          const errorMessage = error.response?.data?.message || error.message || 'Failed to fetch date absences';
          set({
            error: errorMessage,
            loading: false,
          });
          throw error;
        }
      },

      fetchAbsencesForMonth: async (year: number, month: number, statuses?: string[]) => {
        set({ loading: true, error: null });
        try {
          console.log('Store: fetchAbsencesForMonth called with year:', year, 'month:', month, 'statuses:', statuses);
          
          const response = await calendarRhAbsenceEndpoints.getAbsencesForMonth(year, month, statuses);
          console.log('Store: Month absences API response:', response.data);
          
          const transformedAbsences = response.data.map(transformToFrontendAbsence);
          set({
            calendarAbsences: transformedAbsences,
            loading: false,
          });
          
          return transformedAbsences;
        } catch (error: any) {
          console.error('Store: Month absences API error:', error);
          const errorMessage = error.response?.data?.message || error.message || 'Failed to fetch month absences';
          set({
            error: errorMessage,
            loading: false,
          });
          throw error;
        }
      },

      fetchCalendarStatistics: async (filters: CalendarFilters) => {
        set({ loading: true, error: null });
        try {
          console.log('Store: fetchCalendarStatistics called with filters:', filters);
          
          const response = await calendarRhAbsenceEndpoints.getCalendarStatistics(filters);
          console.log('Store: Calendar statistics API response:', response.data);
          
          set({
            statistics: response.data,
            loading: false,
          });
          
          return response.data;
        } catch (error: any) {
          console.error('Store: Calendar statistics API error:', error);
          const errorMessage = error.response?.data?.message || error.message || 'Failed to fetch calendar statistics';
          set({
            error: errorMessage,
            loading: false,
          });
          throw error;
        }
      },
    }),
    {
      name: 'rh-absence-calendar-store',
    }
  )
); 