import { useState, useEffect } from 'react';
import { CalendarEvent, EventStatus } from '../types/calendar-types';
import { useCalendarStore } from '@/shared/api/stores/hr-service/calendarStore';

export const useEventData = (event: CalendarEvent | undefined, open: boolean) => {
  const [formData, setFormData] = useState<CalendarEvent | null>(null);
  const [status, setStatus] = useState<EventStatus>('PENDING');
  const [selectedAgency, setSelectedAgency] = useState<string | undefined>(event?.agenceId); 
  
  const { 
    drivers,
    agencies,
    collaborators,
    fetchDrivers,
    fetchAgencies,
    fetchCollaboratorsByAgency
  } = useCalendarStore();

  useEffect(() => {
    if (event) {

      const eventData = {
        ...event,
        start: event.start ? new Date(event.start).toISOString() : new Date().toISOString(),
        status: event.status || 'PENDING',
        type: event.type || '',
        employeeName: event.employeeName || '',
        description: event.description || '',
        comments: event.comments || '',
        files: event.files || [],
        agence: event.agence || '' 
      };
      
      
      setFormData(eventData);
      setSelectedAgency(event.agenceId); 
      const newStatus = (event.status || 'PENDING') as EventStatus;
      setStatus(newStatus);
    }
  }, [event]);

  useEffect(() => {
    if (open && formData) {
      fetchDrivers();
      fetchAgencies();
    }
  }, [open, formData, fetchDrivers, fetchAgencies]);

  useEffect(() => {
    if (open && formData?.employeeType === 'SEDENTARY' && formData?.agenceId) {
      fetchCollaboratorsByAgency(formData.agenceId);
    }
  }, [open, formData?.employeeType, formData?.agenceId, fetchCollaboratorsByAgency]);

  useEffect(() => {
    if (open && selectedAgency) {
      fetchCollaboratorsByAgency(selectedAgency);
    }
  }, [open, selectedAgency, fetchCollaboratorsByAgency]);

  return {
    formData,
    setFormData,
    status,
    setStatus,
    drivers,
    agencies,
    collaborators,
    selectedAgency, 
    setSelectedAgency
  };
};
