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

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

  // S'assurer que planning est défini lors du premier rendu
  React.useEffect(() => {
    if (!eventData?.planning && schedules.length > 0) {
      const defaultSchedule =
        schedules.find(
          (schedule) => Number(schedule.id) === Number(selectedSchedule)
        ) || schedules[0];

      setEventData((prev) => ({
        ...prev,
        planning: defaultSchedule.id,
        color: defaultSchedule.color,
      }));
    }
  }, [schedules, selectedSchedule, eventData?.planning]);

  if (!isOpen) return null;

  const recurrenceOptions = [
    { value: RecurrenceType.NONE, label: 'Aucune' },
    { value: RecurrenceType.DAILY, label: 'Quotidienne' },
    { value: RecurrenceType.WEEKLY, label: 'Hebdomadaire' },
    { value: RecurrenceType.MONTHLY, label: 'Mensuelle' },
    /*  { value: RecurrenceType.CUSTOM, label: 'Personnalisée' }, */
  ];

  const daysOfWeek = [
    { value: 1, label: 'Lun' },
    { value: 2, label: 'Mar' },
    { value: 3, label: 'Mer' },
    { value: 4, label: 'Jeu' },
    { value: 5, label: 'Ven' },
    { value: 6, label: 'Sam' },
    { value: 0, label: 'Dim' },
  ];

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

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

    const selectedSchedule = schedules.find((s) => s.id === eventData.planning);

    if (eventData.id) {
      handleUpdateEvent(eventData.id, {
        ...eventData,
        planning: eventData.planning, // S'assurer que planning est bien défini
        color: eventData.color || selectedSchedule?.color,
      });
    } else {
      addEvent({
        ...eventData,
        id: `event-${Date.now()}`,
        planning: eventData.planning, // S'assurer que planning est bien défini
        color: eventData.color || selectedSchedule?.color,
      });
    }
    onClose();
  };

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

  return (
    <Modal
      isOpen={isOpen}
      setIsOpen={onClose}
      title={eventData.id ? "Modifier l'événement" : 'Nouvel événement'}
      modalClassName="w-full max-w-md"
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Titre */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Titre
          </label>
          <input
            type="text"
            value={eventData.title || ''}
            onChange={(e) =>
              setEventData({ ...eventData, title: e.target.value })
            }
            className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
            required
          />
        </div>

        {/* Description */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Description
          </label>
          <textarea
            value={eventData.description || ''}
            onChange={(e) =>
              setEventData({ ...eventData, description: e.target.value })
            }
            className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
            rows="3"
          />
        </div>

        {/* Planning */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Planning
          </label>
          <select
            value={eventData.planning || schedules[0]?.id}
            onChange={(e) => {
              const selectedSchedule = schedules.find(
                (s) => s.id === e.target.value
              );
              setEventData({
                ...eventData,
                planning: e.target.value,
                color: selectedSchedule?.color || '#10b981',
              });
            }}
            className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
            required
          >
            {schedules.map((schedule) => (
              <option key={schedule.id} value={schedule.id}>
                {schedule.name}
              </option>
            ))}
          </select>
        </div>

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

        {/* Récurrence */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Récurrence
          </label>
          <select
            value={eventData.recursionType || RecurrenceType.NONE}
            onChange={(e) => {
              return setEventData({
                ...eventData,
                recursionType: e.target.value,
              });
            }}
            className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
          >
            {recurrenceOptions.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>

        {/* Paramètres de récurrence personnalisée */}
        {eventData.recursionType == RecurrenceType.CUSTOM && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Jours de répétition
            </label>
            <div className="flex gap-2 flex-wrap">
              {daysOfWeek.map((day) => (
                <button
                  key={day.value}
                  type="button"
                  onClick={() => {
                    const days = eventData.selectedDays || [];
                    const newDays = days.includes(day.value)
                      ? days.filter((d) => d !== day.value)
                      : [...days, day.value];
                    setEventData({ ...eventData, selectedDays: newDays });
                  }}
                  className={`px-3 py-1 rounded-full text-sm ${
                    (eventData.selectedDays || []).includes(day.value)
                      ? 'bg-primary/10 text-secondary'
                      : 'bg-gray-100 text-gray-600'
                  }`}
                >
                  {day.label}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Date de fin de récurrence */}
        {eventData.recursionType != RecurrenceType.NONE && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Fin de récurrence
            </label>
            <input
              type="date"
              value={
                eventData.recursionEnd
                  ? format(new Date(eventData.recursionEnd), 'yyyy-MM-dd')
                  : ''
              }
              onChange={(e) =>
                setEventData({
                  ...eventData,
                  recursionEnd: e.target.value
                    ? new Date(e.target.value).toISOString()
                    : null,
                })
              }
              className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        )}

        {/* Dates */}
        <div className="grid grid-cols-1 sm: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={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={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>

        {/* 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"
          />
        </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>
    </Modal>
  );
}
