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

/**
 * 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 const RecurrenceType = Object.freeze({
  NONE: 0,
  DAILY: 1,
  WEEKLY: 2,
  MONTHLY: 3,
  CUSTOM: 4,
});

export const PlanningModes = Object.freeze({
  CLASS_SCHEDULE: 'classSchedule',
  PLANNING: 'planning'
});

const CLASS_SCHEDULE_COLORS = [
  '#EF4444',
  '#3B82F6',
  '#F59E0B',
  '#8B5CF6',
  '#EC4899',
  '#14B8A6',
  '#F97316',
  '#6366F1',
  '#06B6D4',
  '#84CC16',
];

const getClassScheduleColor = (schoolClassId) => {
  const numericId = Number(schoolClassId);
  if (!Number.isFinite(numericId) || numericId <= 0) {
    return '#10b981';
  }

  const index = (numericId - 1) % CLASS_SCHEDULE_COLORS.length;
  return CLASS_SCHEDULE_COLORS[index];
};

export function PlanningProvider({
  children,
  modeSet = PlanningModes.PLANNING,
  readOnly = false
}) {
  const [events, setEvents] = useState([]);
  const [schedules, setSchedules] = useState([]);
  const [selectedSchedule, setSelectedSchedule] = useState(0);
  const [planningMode, setPlanningMode] = useState(modeSet);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [viewType, setViewType] = useState('week'); // Changer 'month' en 'week'
  const [parentView, setParentView] = useState(readOnly);
  const [hiddenSchedules, setHiddenSchedules] = useState([]);
  const { selectedEstablishmentId } = useEstablishment();

  const csrfToken = useCsrfToken();
  useEffect(() => {
    reloadPlanning();
    reloadEvents();
  }, [planningMode, selectedEstablishmentId]);

  const reloadEvents = () => {
    fetchEvents(selectedEstablishmentId, planningMode).then((data) => {
      setEvents(data);
    });
  };

  const reloadPlanning = () => {
    fetchPlannings(selectedEstablishmentId, planningMode).then((data) => {
      const normalizedSchedules =
        planningMode === PlanningModes.CLASS_SCHEDULE
          ? data.map((schedule) => ({
              ...schedule,
              color: getClassScheduleColor(schedule.school_class),
            }))
          : data;

      setSchedules(normalizedSchedules);
      if (data.length > 0) {
        setSelectedSchedule(data[0].id);
      }
    });
  };
  const addEvent = (newEvent) => {
    createEvent(newEvent).then(() => {
      reloadEvents();
    });
  };

  const handleUpdateEvent = (id, updatedEvent) => {
    updateEvent(id, updatedEvent, csrfToken).then((data) => {
      reloadEvents();
    });
  };

  const handleDeleteEvent = (id) => {
    deleteEvent(id, csrfToken).then((data) => {
      reloadEvents();
    });
  };

  const addSchedule = (newSchedule) => {
    logger.debug('newSchedule', newSchedule);
    newSchedule.establishment = selectedEstablishmentId;
    createPlanning(newSchedule, csrfToken).then((_) => {
      reloadPlanning();
    });
  };

  const updateSchedule = (id, updatedSchedule) => {
    updatePlanning(id, updatedSchedule, csrfToken).then((data) => {
      reloadPlanning();
    });
  };

  const deleteSchedule = (id) => {
    deletePlanning(id, csrfToken).then((data) => {
      reloadPlanning();
      reloadEvents();
    });
  };

  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,
    setHiddenSchedules,
    toggleScheduleVisibility,
    planningMode,
    reloadEvents,
    reloadPlanning,
    parentView
  };

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

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