import { useState } from 'react';
import { usePlanning, PlanningModes } from '@/context/PlanningContext';
import { Plus, Edit2, Eye, EyeOff, Check, X } from 'lucide-react';
import logger from '@/utils/logger';

export default function ScheduleNavigation({ classes, modeSet = 'event', isOpen = false, onClose = () => {} }) {
  const {
    schedules,
    selectedSchedule,
    setSelectedSchedule,
    hiddenSchedules,
    toggleScheduleVisibility,
    addSchedule,
    updateSchedule,
    planningMode,
  } = usePlanning();
  const [editingId, setEditingId] = useState(null);
  const [editedName, setEditedName] = useState('');
  const [editedColor, setEditedColor] = useState('');
  const [editedSchoolClass, setEditedSchoolClass] = useState(null);
  const [isAddingNew, setIsAddingNew] = useState(false);
  const [newSchedule, setNewSchedule] = useState({
    name: '',
    color: '#10b981',
    school_class: '', // Ajout du champ pour la classe
  });

  const handleEdit = (schedule) => {
    setEditingId(schedule.id);
    setEditedName(schedule.name);
    setEditedColor(schedule.color);
    setEditedSchoolClass(schedule.school_class);
  };

  const handleSave = () => {
    if (editingId) {
      updateSchedule(editingId, {
        ...schedules.find((s) => s.id === editingId),
        name: editedName,
        color: editedColor,
        school_class: editedSchoolClass, // Ajout de l'ID de la classe
      });
      setEditingId(null);
    }
  };

  const handleAddNew = () => {
    if (newSchedule.name) {
      let payload = {
        name: newSchedule.name,
        color: newSchedule.color,
      };
      if (planningMode === PlanningModes.CLASS_SCHEDULE) {
        payload.school_class = newSchedule.school_class; // Ajout de l'ID de la classe
      }
      addSchedule({
        id: `schedule-${Date.now()}`,
        ...payload,
      });
      setIsAddingNew(false);
      setNewSchedule({ name: '', color: '#10b981', school_class: '' });
    }
  };

  const title = planningMode === PlanningModes.CLASS_SCHEDULE ? 'Emplois du temps' : 'Plannings';

  const listContent = (
    <>
      {isAddingNew && (
        <div className="mb-4 p-2 border rounded">
          <input
            type="text"
            value={newSchedule.name}
            onChange={(e) =>
              setNewSchedule((prev) => ({ ...prev, name: e.target.value }))
            }
            className="w-full p-1 mb-2 border rounded"
            placeholder={
              planningMode === PlanningModes.CLASS_SCHEDULE
                ? "Nom de l'emplois du temps"
                : 'Nom du planning'
            }
          />
          <div className="flex gap-2 items-center mb-2">
            <label className="text-sm">Couleur:</label>
            <input
              type="color"
              value={newSchedule.color}
              onChange={(e) =>
                setNewSchedule((prev) => ({ ...prev, color: e.target.value }))
              }
              className="w-8 h-8"
            />
          </div>
          {planningMode === PlanningModes.CLASS_SCHEDULE && (
            <div className="mb-2">
              <label className="text-sm">Classe (optionnel):</label>
              <select
                value={newSchedule.school_class}
                onChange={(e) =>
                  setNewSchedule((prev) => ({
                    ...prev,
                    school_class: e.target.value,
                  }))
                }
                className="w-full p-1 border rounded"
              >
                <option value="">Aucune</option>
                {classes.map((classe) => {
                  logger.debug({ classe });
                  return (
                    <option key={classe.id} value={classe.id}>
                      {classe.atmosphere_name}
                    </option>
                  );
                })}
              </select>
            </div>
          )}
          <div className="flex justify-end gap-2">
            <button
              onClick={() => setIsAddingNew(false)}
              className="p-1 hover:bg-gray-100 rounded"
            >
              <X className="w-4 h-4" />
            </button>
            <button
              onClick={handleAddNew}
              className="p-1 hover:bg-gray-100 rounded"
            >
              <Check className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      <ul className="space-y-2">
        {schedules.map((schedule) => (
          <li
            key={schedule.id}
            className={`p-2 rounded ${
              selectedSchedule === schedule.id
                ? 'bg-gray-100'
                : 'hover:bg-gray-50'
            }`}
          >
            {editingId === schedule.id ? (
              <div className="space-y-2">
                <input
                  type="text"
                  value={editedName}
                  onChange={(e) => setEditedName(e.target.value)}
                  className="w-full p-1 border rounded"
                />
                <div className="flex gap-2 items-center">
                  <label className="text-sm">Couleur:</label>
                  <input
                    type="color"
                    value={editedColor}
                    onChange={(e) => setEditedColor(e.target.value)}
                    className="w-8 h-8"
                  />
                </div>
                {planningMode === PlanningModes.CLASS_SCHEDULE && (
                  <div className="mb-2">
                    <label className="text-sm">Classe:</label>
                    <select
                      value={editedSchoolClass}
                      onChange={(e) => setEditedSchoolClass(e.target.value)}
                      className="w-full p-1 border rounded"
                    >
                      <option value="">Aucune</option>
                      {classes.map((classe) => (
                        <option key={classe.id} value={classe.id}>
                          {classe.atmosphere_name}
                        </option>
                      ))}
                    </select>
                  </div>
                )}
                <div className="flex justify-end gap-2">
                  <button
                    onClick={() => setEditingId(null)}
                    className="p-1 hover:bg-gray-100 rounded"
                  >
                    <X className="w-4 h-4" />
                  </button>
                  <button
                    onClick={handleSave}
                    className="p-1 hover:bg-gray-100 rounded"
                  >
                    <Check className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-between">
                <div
                  className="flex items-center gap-2 flex-1 cursor-pointer"
                  onClick={() => setSelectedSchedule(schedule.id)}
                >
                  <div
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: schedule.color }}
                  />
                  <span
                    className={
                      hiddenSchedules.includes(schedule.id)
                        ? 'text-gray-400'
                        : ''
                    }
                  >
                    {schedule.name}
                  </span>
                </div>
                <div className="flex gap-1">
                  <button
                    onClick={(e) => {
                      e.stopPropagation(); // Empêcher la propagation du clic
                      toggleScheduleVisibility(schedule.id);
                    }}
                    className="p-1 hover:bg-gray-100 rounded"
                  >
                    {hiddenSchedules.includes(schedule.id) ? (
                      <EyeOff className="w-4 h-4" />
                    ) : (
                      <Eye className="w-4 h-4" />
                    )}
                  </button>
                  <button
                    onClick={() => handleEdit(schedule)}
                    className="p-1 hover:bg-gray-100 rounded"
                  >
                    <Edit2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            )}
          </li>
        ))}
      </ul>
    </>
  );

  return (
    <>
      {/* Desktop : sidebar fixe */}
      <nav className="hidden md:flex flex-col w-64 border-r p-4 h-full overflow-y-auto shrink-0">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-headline font-semibold">{title}</h2>
          <button onClick={() => setIsAddingNew(true)} className="p-1 hover:bg-gray-100 rounded">
            <Plus className="w-4 h-4" />
          </button>
        </div>
        {listContent}
      </nav>

      {/* Mobile : drawer en overlay */}
      <div
        className={`md:hidden fixed inset-0 z-50 transition-opacity duration-200 ${
          isOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
        }`}
      >
        <div className="absolute inset-0 bg-black/40" onClick={onClose} />
        <div
          className={`absolute left-0 top-0 bottom-0 w-72 bg-white shadow-xl flex flex-col transition-transform duration-200 ${
            isOpen ? 'translate-x-0' : '-translate-x-full'
          }`}
        >
          <div className="flex items-center justify-between p-4 border-b shrink-0">
            <h2 className="font-headline font-semibold">{title}</h2>
            <div className="flex items-center gap-1">
              <button onClick={() => setIsAddingNew(true)} className="p-1 hover:bg-gray-100 rounded">
                <Plus className="w-4 h-4" />
              </button>
              <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>
          <div className="flex-1 overflow-y-auto p-4">
            {listContent}
          </div>
        </div>
      </div>
    </>
  );
}
