import { usePlanning } from '@/context/PlanningContext';
import { format } from 'date-fns';
import React from 'react';
import { useNotification } from '@/context/NotificationContext';

export default function ScheduleEventModal({
  isOpen,
  onClose,
  eventData,
  setEventData,
  specialities,
  teachers,
  classes,
}) {
  const {
    addEvent,
    handleUpdateEvent,
    handleDeleteEvent,
    schedules,
    selectedSchedule,
  } =
    usePlanning();
  const { showNotification } = useNotification();

  const selectedPlanning = React.useMemo(() => {
    return schedules.find(
      (schedule) => Number(schedule.id) === Number(eventData?.planning)
    );
  }, [schedules, eventData?.planning]);

  const selectedClass = React.useMemo(() => {
    if (!selectedPlanning?.school_class) {
      return null;
    }

    return classes.find(
      (schoolClass) =>
        Number(schoolClass.id) === Number(selectedPlanning.school_class)
    );
  }, [classes, selectedPlanning]);

  const classTeachers = React.useMemo(() => {
    if (!selectedClass) {
      return teachers;
    }

    const classTeacherIds = [
      ...(Array.isArray(selectedClass.teachers) ? selectedClass.teachers : []),
      ...((selectedClass.teachers_details || []).map((teacher) => teacher.id) || []),
    ];

    if (classTeacherIds.length === 0) {
      return [];
    }

    const classTeacherIdSet = new Set(classTeacherIds.map((id) => Number(id)));
    return teachers.filter((teacher) => classTeacherIdSet.has(Number(teacher.id)));
  }, [teachers, selectedClass]);

  const classSpecialities = React.useMemo(() => {
    const specialityMap = new Map();

    classTeachers.forEach((teacher) => {
      (teacher.specialities_details || []).forEach((speciality) => {
        specialityMap.set(Number(speciality.id), speciality);
      });

      (teacher.specialities || []).forEach((specialityId) => {
        if (specialityMap.has(Number(specialityId))) {
          return;
        }

        const speciality = specialities.find(
          (item) => Number(item.id) === Number(specialityId)
        );
        if (speciality) {
          specialityMap.set(Number(speciality.id), speciality);
        }
      });
    });

    return Array.from(specialityMap.values());
  }, [classTeachers, specialities]);

  React.useEffect(() => {
    if (!eventData?.planning && schedules.length > 0) {
      const defaultSchedule =
        schedules.find(
          (schedule) => Number(schedule.id) === Number(selectedSchedule)
        ) || schedules[0];
      if (eventData?.planning !== defaultSchedule.id) {
        setEventData((prev) => ({
          ...prev,
          planning: defaultSchedule.id,
        }));
      }
    }
  }, [schedules, selectedSchedule, eventData?.planning]);

  React.useEffect(() => {
    if (
      eventData?.teacher &&
      !classTeachers.some(
        (teacher) => Number(teacher.id) === Number(eventData.teacher)
      )
    ) {
      setEventData((prev) => ({
        ...prev,
        teacher: '',
      }));
    }

    if (
      eventData?.speciality &&
      !classSpecialities.some(
        (speciality) => Number(speciality.id) === Number(eventData.speciality)
      )
    ) {
      setEventData((prev) => ({
        ...prev,
        speciality: '',
      }));
    }
  }, [classTeachers, classSpecialities, eventData?.teacher, eventData?.speciality]);

  const handleSpecialityChange = (specialityId) => {
    const selectedSpeciality = classSpecialities.find(
      (s) => Number(s.id) === Number(specialityId)
    );
    if (selectedSpeciality) {
      setEventData((prev) => ({
        ...prev,
        speciality: selectedSpeciality.id,
        title: selectedSpeciality.name, // Définit la matière
        color: selectedSpeciality.color_code, // Définit la couleur associée
      }));
    }
  };

  const handleTeacherChange = (teacherId) => {
    const selectedTeacher = classTeachers.find(
      (t) => Number(t.id) === Number(teacherId)
    );
    if (selectedTeacher) {
      setEventData((prev) => ({
        ...prev,
        teacher: selectedTeacher.id,
        description: `${selectedTeacher.first_name} ${selectedTeacher.last_name}`, // Définit le nom du professeur
      }));
    }
  };

  const handlePlanningChange = (planningId) => {
    const selectedSchedule = schedules.find(
      (s) => Number(s.id) === Number(planningId)
    );
    if (selectedSchedule) {
      setEventData((prev) => ({
        ...prev,
        planning: selectedSchedule.id,
      }));
    }
  };

  const handleColorChange = (color) => {
    setEventData((prev) => ({
      ...prev,
      color, // Permet de changer manuellement la couleur
    }));
  };

  if (!isOpen) return null;

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!eventData.speciality) {
      showNotification(
        'Veuillez sélectionner une matière',
        'warning',
        'Attention'
      );
      return;
    }

    if (!eventData.teacher) {
      showNotification(
        'Veuillez sélectionner un professeur',
        'warning',
        'Attention'
      );
      return;
    }

    if (!eventData.planning) {
      showNotification(
        'Veuillez sélectionner un planning',
        'warning',
        'Attention'
      );
      return;
    }

    if (!eventData.location) {
      showNotification('Veuillez saisir un lieu', 'warning', 'Attention');
      return;
    }

    if (eventData.id) {
      handleUpdateEvent(eventData.id, eventData);
    } else {
      addEvent({
        ...eventData,
        id: `event-${Date.now()}`,
      });
    }
    onClose();
  };

  const handleDelete = () => {
    if (
      eventData.id &&
      confirm('Êtes-vous sûr de vouloir supprimer cet événement ?')
    ) {
      handleDeleteEvent(eventData.id);
      onClose();
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white p-6 rounded-lg w-full max-w-md">
        <h2 className="font-headline text-xl font-semibold mb-4">
          {eventData.id ? "Modifier l'événement" : 'Nouvel événement'}
        </h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Planning */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Planning
            </label>
            <select
              value={eventData.planning || ''}
              onChange={(e) => handlePlanningChange(e.target.value)}
              className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
              required
            >
              <option value="" disabled>
                Sélectionnez un planning
              </option>
              {schedules.map((schedule) => (
                <option key={schedule.id} value={schedule.id}>
                  {schedule.name}
                </option>
              ))}
            </select>
          </div>

          {/* Matière */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Matière
            </label>
            <select
              value={eventData.speciality || ''}
              onChange={(e) => handleSpecialityChange(e.target.value)}
              className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
              required
            >
              <option value="" disabled>
                Sélectionnez une matière
              </option>
              {classSpecialities.map((speciality) => (
                <option key={speciality.id} value={speciality.id}>
                  {speciality.name}
                </option>
              ))}
            </select>
          </div>

          {/* Professeur */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Professeur
            </label>
            <select
              value={eventData.teacher || ''}
              onChange={(e) => handleTeacherChange(e.target.value)}
              className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
              required
            >
              <option value="" disabled>
                Sélectionnez un professeur
              </option>
              {classTeachers.map((teacher) => (
                <option key={teacher.id} value={teacher.id}>
                  {`${teacher.first_name} ${teacher.last_name}`}
                </option>
              ))}
            </select>
          </div>

          {/* Lieu */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Lieu
            </label>
            <input
              type="text"
              value={eventData.location || ''}
              onChange={(e) =>
                setEventData({ ...eventData, location: e.target.value })
              }
              className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="Saisissez un lieu"
              required
            />
          </div>

          {/* Couleur */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Couleur
            </label>
            <input
              type="color"
              value={eventData.color || '#10b981'}
              onChange={(e) => handleColorChange(e.target.value)}
              className="w-full h-10 p-1 rounded border"
            />
          </div>

          {/* Dates */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Début
              </label>
              <input
                type="datetime-local"
                value={
                  eventData.start
                    ? format(new Date(eventData.start), "yyyy-MM-dd'T'HH:mm")
                    : ''
                }
                onChange={(e) =>
                  setEventData({
                    ...eventData,
                    start: new Date(e.target.value).toISOString(),
                  })
                }
                className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Fin
              </label>
              <input
                type="datetime-local"
                value={
                  eventData.end
                    ? format(new Date(eventData.end), "yyyy-MM-dd'T'HH:mm")
                    : ''
                }
                onChange={(e) =>
                  setEventData({
                    ...eventData,
                    end: new Date(e.target.value).toISOString(),
                  })
                }
                className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
                required
              />
            </div>
          </div>

          {/* Boutons */}
          <div className="flex justify-between gap-2 mt-6">
            <div>
              {eventData.id && (
                <button
                  type="button"
                  onClick={handleDelete}
                  className="px-4 py-2 text-red-600 hover:bg-red-50 rounded"
                >
                  Supprimer
                </button>
              )}
            </div>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded"
              >
                Annuler
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-primary text-white rounded hover:bg-secondary"
              >
                {eventData.id ? 'Modifier' : 'Créer'}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
