import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { calendarEndpoints } from '../../endpoints/hr/calendar/calendar';
import { IDriver } from '@/shared/types/driver';
import { IAgency } from '@/shared/types/infrastructure';
import { CollaboratorDTO } from '@/shared/types/collaborator'; 

export interface CalendarEventResponse {
  id: string;
  employeeType: 'DRIVER' | 'SEDENTARY';
  employeeName: string;
  type: string;
  agence: string;
  employeeId?: string;
  date: string;
  hour?: string;
  notes?: string;
  notifications: string[];
  isAllDay: boolean;
  files: string[];
  status:string;
}

export interface CreateEventRequest {
  employeeType: 'DRIVER' | 'SEDENTARY';
  type: string;
  employeeId?: string;
  agenceId?: string;
  date: string;
  hour?: string;
  notes?: string;
  notifications: string[];
  isAllDay: boolean;
  status:String;
}



interface CalendarStore {
  events: CalendarEventResponse[];
  loading: boolean;
  error: string | null;
  drivers: IDriver[];
  agencies: IAgency[];
  notificationIntervals: Array<{ value: string; label: string }>;
  collaborators: CollaboratorDTO[];
  
  fetchEvents: () => Promise<void>;
  createEvent: (eventData: CreateEventRequest) => Promise<CalendarEventResponse>;
  updateEvent: (id:number,eventData:CreateEventRequest ) => Promise<CalendarEventResponse>;
  deleteEvent: (id: string | number) => Promise<void>;
  fetchDrivers: () => Promise<void>;
  fetchAgencies: () => Promise<void>;
  fetchNotificationIntervals: () => Promise<void>;
  fetchCollaboratorsByAgency: (agencyId: string) => Promise<void>;
}

export const useCalendarStore = create<CalendarStore>((set, get) => ({
  events: [],
  loading: false,
  error: null,
  drivers: [],
  agencies: [],
  notificationIntervals: [],
  collaborators: [],

  fetchEvents: async () => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(calendarEndpoints.events.getAll);
      set({ events: response.data, loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || 'Erreur lors du chargement des événements', 
        loading: false 
      });
    }
  },

  createEvent: async (eventData: CreateEventRequest) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post(calendarEndpoints.events.create, eventData);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || 'Erreur lors de la création de l\'événement', 
        loading: false 
      });
      throw error;
    }
  },

  updateEvent: async (id: number, eventData: CreateEventRequest) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.put(calendarEndpoints.events.update(id), eventData);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || 'Erreur lors de la mise à jour de l\'événement', 
        loading: false 
      });
      throw error;
    }
  },

  deleteEvent: async (id: string | number) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.delete(calendarEndpoints.events.delete(id));
      set({ loading: false });
    } catch (error: any) {
      set({ 
        error: error.response?.data?.message || 'Erreur lors de la suppression de l\'événement', 
        loading: false 
      });
      throw error;
    }
  },

  fetchDrivers: async () => {
    try {
      const response = await axiosInstance.get(calendarEndpoints.employees.getDrivers);
      set({ drivers: response.data || [] });
    } catch (error: any) {
      console.error('Erreur lors du chargement des chauffeurs:', error);
      set({ drivers: [] });
    }
  },

  fetchAgencies: async () => {
    try {
      const response = await axiosInstance.get(calendarEndpoints.employees.getAgencies);
      set({ agencies: response.data || [] });
    } catch (error: any) {
      console.error('Erreur lors du chargement des agences:', error);
      set({ agencies: [] });
    }
  },

  fetchNotificationIntervals: async () => {
    try {
      const response = await axiosInstance.get(calendarEndpoints.notifications.getIntervals);
      set({ notificationIntervals: response.data || [] });
    } catch (error: any) {
      console.error('Erreur lors du chargement des intervalles de notification:', error);
      set({ 
        notificationIntervals: [
          { value: '15min', label: '15 minutes avant' },
          { value: '30min', label: '30 minutes avant' },
          { value: '1hour', label: '1 heure avant' },
          { value: '1day', label: '1 jour avant' },
          { value: '1week', label: '1 semaine avant' }
        ] 
      });
    }
  },

  fetchCollaboratorsByAgency: async (agencyId: string) => {
    try {
      const response = await axiosInstance.get(`api/user/collaborators/collaborators/agency/${agencyId}`);
      set({ collaborators: response.data || [] });
    } catch (error: any) {
      console.error('Erreur lors du chargement des collaborateurs:', error);
      set({ collaborators: [] });
    }
  },
})); 