import { createContext, useContext, useEffect, useState } from 'react';
import { createPlanning, fetchEvents, fetchPlannings, updatePlanning, createEvent, deleteEvent, updateEvent } from '@/app/actions/planningAction';
import { useCsrfToken } from './CsrfContext';
import { ESTABLISHMENT_ID } from '@/utils/Url';
import logger from '@/utils/logger';



/**
 * Contexte de planification pour gérer l'état global du planning
 * Fournit des fonctionnalités pour :
 * - Gestion des événements (ajout, modification, suppression)
 * - Gestion des emplois du temps (ajout, modification, suppression)
 * - Gestion de la visibilité des emplois du temps
 * - Contrôle de la vue du calendrier (date courante, type de vue)
 * - Stockage de l'état des événements et des emplois du temps
 */
const PlanningContext = createContext();

export function PlanningProvider({ children }) {
  // const [events, setEvents] = useState([]);
  // const [schedules, setSchedules] = useState([]);
  // const [selectedSchedule, setSelectedSchedule] = useState(null);
  const [events, setEvents] = useState([]);
  const [schedules, setSchedules] = useState([]);
  const [selectedSchedule, setSelectedSchedule] = useState(0);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [viewType, setViewType] = useState('week'); // Changer 'month' en 'week'
  const [hiddenSchedules, setHiddenSchedules] = useState([]);

   const csrfToken = useCsrfToken();
   useEffect(()=>{

    fetchPlannings().then((data) => {
     setSchedules(data)
     setSelectedSchedule(data[0].id);
    });
    fetchEvents().then((data)=>{
      setEvents(data);
    });
   },[]);




  const addEvent = (newEvent) => {
    createEvent(newEvent).then((data) => {
      setEvents((prevEvents) => [...prevEvents, data]);
    });
    console.log('newEvent',newEvent);

    //dssetEvents((prevEvents) => [...prevEvents, newEvent]);
  };

  const handleUpdateEvent = (id, updatedEvent) => {
    updateEvent(id,updatedEvent,csrfToken).then((data) => {
        setEvents((prevEvents) =>
          prevEvents.map((event) => (event.id === id ? updatedEvent : event))
        );
    });

  };

  const handleDeleteEvent = (id) => {
    deleteEvent(id,csrfToken).then((data) => {
      setEvents((prevEvents) => prevEvents.filter((event) => event.id !== id));
    });

  };

  const addSchedule = (newSchedule) => {
    //FIXME:Gerenr lestablshment
    logger.debug('newSchedule',newSchedule);
    newSchedule.establishment = ESTABLISHMENT_ID;

    createPlanning(newSchedule,csrfToken).then((data) => {
      setSchedules((prevSchedules) => [...prevSchedules, data]);
    });
  };

  const updateSchedule = (id, updatedSchedule) => {

    updatePlanning(id,updatedSchedule,csrfToken).then((data) => {
        setSchedules((prevSchedules) =>
        prevSchedules.map((schedule) =>
          schedule.id === id ? updatedSchedule : schedule
        )
      );
    });
  };

  const deleteSchedule = (id) => {
    deletePlanning(id,csrfToken).then((data) => {
      setSchedules((prevSchedules) =>
        prevSchedules.filter((schedule) => schedule.id !== id)
      );
    }
    );

  };

  const toggleScheduleVisibility = (planning) => {
    setHiddenSchedules((prev) => {
      const isHidden = prev.includes(planning);
      const newHiddenSchedules = isHidden
        ? prev.filter((id) => id !== planning)
        : [...prev, planning];
      return newHiddenSchedules;
    });
  };

  const value = {
    events,
    setEvents,
    schedules,
    setSchedules,
    selectedSchedule,
    setSelectedSchedule,
    addEvent,
    handleUpdateEvent,
    handleDeleteEvent,
    addSchedule,
    updateSchedule,
    deleteSchedule,
    currentDate,
    setCurrentDate,
    viewType,
    setViewType,
    hiddenSchedules,
    toggleScheduleVisibility
  };

  return (
    <PlanningContext.Provider value={value}>
      {children}
    </PlanningContext.Provider>
  );
}

export const usePlanning = () => useContext(PlanningContext);