import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import type { IWorkingHours, CreateWorkingHoursRequest, UpdateWorkingHoursRequest } from '@/shared/types/working-hours';
import { workingHoursApi } from '@/shared/api/endpoints/hr/working-hours';

interface WorkingHoursState {

  workingHours: IWorkingHours[];
  currentEmployeeWorkingHours: IWorkingHours[];

  loading: boolean;
  creating: boolean;
  updating: boolean;
  deleting: boolean;
  

  error: string | null;
  

  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;

  fetchWorkingHoursByEmployeeId: (employeeId: string) => Promise<IWorkingHours[]>;
  fetchWorkingHoursByDay: (day: number) => Promise<IWorkingHours[]>;
  getAvailableEmployees: (day: number, startHour: number, endHour: number) => Promise<string[]>;
  createWorkingHours: (request: CreateWorkingHoursRequest) => Promise<IWorkingHours>;
  updateWorkingHours: (id: string, request: UpdateWorkingHoursRequest) => Promise<IWorkingHours>;
  deleteWorkingHours: (id: string) => Promise<boolean>;
  deleteAllWorkingHoursByEmployeeId: (employeeId: string) => Promise<boolean>;
  
  // Utility actions
  clearCurrentEmployeeWorkingHours: () => void;
  clearError: () => void;
}

export const useWorkingHoursStore = create<WorkingHoursState>()(
  devtools(
    (set, get) => ({

      workingHours: [],
      currentEmployeeWorkingHours: [],
      loading: false,
      creating: false,
      updating: false,
      deleting: false,
      
  
      error: null,
    
      setLoading: (loading) => set({ loading }),
      setError: (error) => set({ error }),
      

      fetchWorkingHoursByEmployeeId: async (employeeId: string) => {
        set({ loading: true, error: null });
        
        try {
          const response = await workingHoursApi.getWorkingHoursByEmployeeId(employeeId);
          const workingHours = response.data;
          
          set({
            currentEmployeeWorkingHours: workingHours,
            loading: false,
          });
          
          return workingHours;
        } catch (error: any) {
          console.error('Error fetching working hours:', error);
          set({
            error: error.message || 'Failed to fetch working hours',
            loading: false,
          });
          return [];
        }
      },
      
      fetchWorkingHoursByDay: async (day: number) => {
        set({ loading: true, error: null });
        
        try {
          const response = await workingHoursApi.getWorkingHoursByDay(day);
          const workingHours = response.data;
          
          set({
            workingHours,
            loading: false,
          });
          
          return workingHours;
        } catch (error: any) {
          console.error('Error fetching working hours by day:', error);
          set({
            error: error.message || 'Failed to fetch working hours by day',
            loading: false,
          });
          return [];
        }
      },
      
      getAvailableEmployees: async (day: number, startHour: number, endHour: number) => {
        set({ loading: true, error: null });
        
        try {
          const response = await workingHoursApi.getAvailableEmployees(day, startHour, endHour);
          const availableEmployees = response.data;
          
          set({ loading: false });
          return availableEmployees;
        } catch (error: any) {
          console.error('Error getting available employees:', error);
          set({
            error: error.message || 'Failed to get available employees',
            loading: false,
          });
          return [];
        }
      },
      
      createWorkingHours: async (request: CreateWorkingHoursRequest) => {
        set({ creating: true, error: null });
        
        try {
          const response = await workingHoursApi.createWorkingHours(request);
          const newWorkingHours = response.data;
          
          set((state) => ({
            currentEmployeeWorkingHours: [...state.currentEmployeeWorkingHours, newWorkingHours],
            creating: false,
          }));
          
          return newWorkingHours;
        } catch (error: any) {
          console.error('Error creating working hours:', error);
          set({
            error: error.message || 'Failed to create working hours',
            creating: false,
          });
          throw error;
        }
      },
      
      updateWorkingHours: async (id: string, request: UpdateWorkingHoursRequest) => {
        set({ updating: true, error: null });
        
        try {
          const response = await workingHoursApi.updateWorkingHours(id, request);
          const updatedWorkingHours = response.data;
          
          set((state) => ({
            currentEmployeeWorkingHours: state.currentEmployeeWorkingHours.map(wh =>
              wh.id === id ? updatedWorkingHours : wh
            ),
            updating: false,
          }));
          
          return updatedWorkingHours;
        } catch (error: any) {
          console.error('Error updating working hours:', error);
          set({
            error: error.message || 'Failed to update working hours',
            updating: false,
          });
          throw error;
        }
      },
      
      deleteWorkingHours: async (id: string) => {
        set({ deleting: true, error: null });
        
        try {
          await workingHoursApi.deleteWorkingHours(id);
          
          set((state) => ({
            currentEmployeeWorkingHours: state.currentEmployeeWorkingHours.filter(wh => wh.id !== id),
            deleting: false,
          }));
          
          return true;
        } catch (error: any) {
          console.error('Error deleting working hours:', error);
          set({
            error: error.message || 'Failed to delete working hours',
            deleting: false,
          });
          return false;
        }
      },
      
      deleteAllWorkingHoursByEmployeeId: async (employeeId: string) => {
        set({ deleting: true, error: null });
        
        try {
          await workingHoursApi.deleteAllWorkingHoursByEmployeeId(employeeId);
          
          set({
            currentEmployeeWorkingHours: [],
            deleting: false,
          });
          
          return true;
        } catch (error: any) {
          console.error('Error deleting all working hours:', error);
          set({
            error: error.message || 'Failed to delete all working hours',
            deleting: false,
          });
          return false;
        }
      },
      
      // Utility actions
      clearCurrentEmployeeWorkingHours: () => set({ currentEmployeeWorkingHours: [] }),
      clearError: () => set({ error: null }),
    }),
    {
      name: 'working-hours-store',
    }
  )
);

