'use client';

import React, { useState } from 'react';

import { RecurrenceType, usePlanning } from '@/context/PlanningContext';
import Calendar from '@/components/Calendar/Calendar';
import ScheduleEventModal from '@/components/Structure/Planning/ScheduleEventModal';
import ScheduleNavigation from '@/components/Calendar/ScheduleNavigation';

export default function ScheduleManagement({
  classes,
  specialities,
  teachers,
}) {
  const { selectedSchedule, schedules } = usePlanning();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [eventData, setEventData] = useState({
    title: '',
    description: '',
    start: '',
    end: '',
    location: '',
    planning: '', // Enlever la valeur par défaut ici
    recursionType: RecurrenceType.NONE,
    selectedDays: [],
    recursionEnd: '',
    customInterval: 1,
    customUnit: 'days',
    viewType: 'week', // Ajouter la vue semaine par défaut
  });

  const initializeNewEvent = (date = new Date()) => {
    // S'assurer que date est un objet Date valide
    const eventDate = date instanceof Date ? date : new Date();

    const selected =
      schedules.find((schedule) => Number(schedule.id) === Number(selectedSchedule)) ||
      schedules[0];

    setEventData({
      title: '',
      description: '',
      start: eventDate.toISOString(),
      end: new Date(eventDate.getTime() + 2 * 60 * 60 * 1000).toISOString(),
      location: '',
      planning: selected?.id || '',
      color: selected?.color || '',
      recursionType: RecurrenceType.NONE,
      selectedDays: [],
      recursionEnd: new Date(
        eventDate.getTime() + 2 * 60 * 60 * 1000
      ).toISOString(),
      customInterval: 1,
      customUnit: 'days',
    });
    setIsModalOpen(true);
  };

  return (
    <div className="flex h-full overflow-hidden">
      <ScheduleNavigation classes={classes} />
      <Calendar
        onDateClick={initializeNewEvent}
        onEventClick={(event) => {
          setEventData(event);
          setIsModalOpen(true);
        }}
      />
      <ScheduleEventModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        eventData={eventData}
        setEventData={setEventData}
        specialities={specialities}
        teachers={teachers}
        classes={classes}
      />
    </div>
  );
}
