import { useCallback, useState } from 'react';
import { useWorkingHoursStore } from '@/shared/api/stores/hr-service/workingHoursStore';
import type { WorkingHoursSlot, CreateWorkingHoursRequest } from '@/shared/types/working-hours';
import { useSnackbar } from 'notistack';

export const useWorkingHours = (employeeId?: string) => {
  const { enqueueSnackbar } = useSnackbar();
  const [workingHoursSlots, setWorkingHoursSlots] = useState<WorkingHoursSlot[]>([]);
  
  const {
    currentEmployeeWorkingHours,
    loading,
    creating,
    updating,
    deleting,
    error,
    fetchWorkingHoursByEmployeeId,
    createWorkingHours,
    updateWorkingHours,
    deleteWorkingHours,
    deleteAllWorkingHoursByEmployeeId,
    clearCurrentEmployeeWorkingHours,
    clearError,
  } = useWorkingHoursStore();

  const loadWorkingHours = useCallback(async (id: string) => {
    try {
      const workingHours = await fetchWorkingHoursByEmployeeId(id);
      
      const slots: WorkingHoursSlot[] = workingHours.map(wh => ({
        id: wh.id,
        dayOfWeek: wh.dayOfWeek,
        startHour: wh.startHour,
        endHour: wh.endHour,
      }));
      setWorkingHoursSlots(slots);
      return slots;
    } catch (error: any) {
      console.error('Error loading working hours:', error);
      enqueueSnackbar('Erreur lors du chargement des heures de travail', { variant: 'error' });
      return [];
    }
  }, [fetchWorkingHoursByEmployeeId, enqueueSnackbar]); // Remove setWorkingHoursSlots from dependencies

  
  const saveWorkingHours = useCallback(async (slots: WorkingHoursSlot[], employeeId: string) => {
    try {
      
      if (currentEmployeeWorkingHours.length > 0) {
        await deleteAllWorkingHoursByEmployeeId(employeeId);
      }
      
      
      const createPromises = slots.map(slot => {
        const request: CreateWorkingHoursRequest = {
          dayOfWeek: slot.dayOfWeek,
          startHour: slot.startHour,
          endHour: slot.endHour,
          employeeId: employeeId,
        };
        return createWorkingHours(request);
      });
      
      await Promise.all(createPromises);
      
      enqueueSnackbar('Heures de travail sauvegardées avec succès', { variant: 'success' });
      return true;
    } catch (error: any) {
      console.error('Error saving working hours:', error);
      enqueueSnackbar('Erreur lors de la sauvegarde des heures de travail', { variant: 'error' });
      return false;
    }
  }, [currentEmployeeWorkingHours.length, deleteAllWorkingHoursByEmployeeId, createWorkingHours, enqueueSnackbar]);

  
  const updateWorkingHoursSlot = useCallback(async (slotId: string, slot: WorkingHoursSlot) => {
    try {
      await updateWorkingHours(slotId, {
        dayOfWeek: slot.dayOfWeek,
        startHour: slot.startHour,
        endHour: slot.endHour,
      });
      
      enqueueSnackbar('Créneau modifié avec succès', { variant: 'success' });
      return true;
    } catch (error: any) {
      console.error('Error updating working hours slot:', error);
      enqueueSnackbar('Erreur lors de la modification du créneau', { variant: 'error' });
      return false;
    }
  }, [updateWorkingHours, enqueueSnackbar]);

  
  const deleteWorkingHoursSlot = useCallback(async (slotId: string) => {
    try {
      const success = await deleteWorkingHours(slotId);
      if (success) {
        enqueueSnackbar('Créneau supprimé avec succès', { variant: 'success' });
      }
      return success;
    } catch (error: any) {
      console.error('Error deleting working hours slot:', error);
      enqueueSnackbar('Erreur lors de la suppression du créneau', { variant: 'error' });
      return false;
    }
  }, [deleteWorkingHours, enqueueSnackbar]);

  const clearWorkingHours = useCallback(() => {
    setWorkingHoursSlots([]);
    clearCurrentEmployeeWorkingHours();
  }, [clearCurrentEmployeeWorkingHours]);

  return {
  
    workingHoursSlots,
    setWorkingHoursSlots,
    currentEmployeeWorkingHours,
    loading,
    creating,
    updating,
    deleting,
    error,
    

    loadWorkingHours,
    saveWorkingHours,
    updateWorkingHoursSlot,
    deleteWorkingHoursSlot,
    clearWorkingHours,
    clearError,
    
    createWorkingHours,
    fetchWorkingHoursByEmployeeId,
    deleteWorkingHours,
  };
};

