/* Hallmark · pre-emit critique: P5 H5 E5 S5 R5 V5 */
/* Hallmark · component: EventFormModal · genre: editorial · theme: Atelier (Dark & Light) */
import React, { useState, useEffect } from 'react';
import { X, Plus, Trash2, Calendar, Layers, Edit3 } from 'lucide-react';

export default function EventFormModal({ eventToEdit, skills, onClose, onSubmit }) {
  const [title, setTitle] = useState(eventToEdit?.title || '');
  const [description, setDescription] = useState(eventToEdit?.description || '');
  const [location, setLocation] = useState(eventToEdit?.location || '');
  const [startDate, setStartDate] = useState(eventToEdit?.start_date || new Date().toISOString().split('T')[0]);
  const [endDate, setEndDate] = useState(eventToEdit?.end_date || new Date().toISOString().split('T')[0]);

  // Task areas state
  const [taskAreas, setTaskAreas] = useState([]);

  useEffect(() => {
    if (eventToEdit && eventToEdit.task_areas && eventToEdit.task_areas.length > 0) {
      const formattedAreas = eventToEdit.task_areas.map(ta => ({
        id: ta.id,
        name: ta.name,
        description: ta.description || '',
        shifts: (ta.shifts || []).map(s => ({
          id: s.id,
          title: s.title,
          start_time: s.start_time,
          end_time: s.end_time,
          max_participants: s.max_participants || 1,
          required_skill_ids: s.required_skills ? s.required_skills.map(sk => sk.id) : []
        }))
      }));
      setTaskAreas(formattedAreas);
    } else if (!eventToEdit) {
      setTaskAreas([
        {
          name: 'Tresendienst',
          description: 'Getränke- und Barverkauf',
          shifts: [{ title: 'Schicht 1', start_time: '18:00', end_time: '22:00', max_participants: 2, required_skill_ids: [] }]
        },
        {
          name: 'Essen kochen',
          description: 'Zubereitung von Speisen',
          shifts: [{ title: 'Frühschicht', start_time: '15:00', end_time: '19:00', max_participants: 3, required_skill_ids: [] }]
        },
        {
          name: 'Aufbau & Aufräumen',
          description: 'Tische, Stühle & Technik',
          shifts: [{ title: 'Aufbau', start_time: '12:00', end_time: '15:00', max_participants: 4, required_skill_ids: [] }]
        }
      ]);
    }
  }, [eventToEdit]);

  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  const addTaskArea = () => {
    setTaskAreas([
      ...taskAreas,
      {
        name: '',
        description: '',
        shifts: [{ title: 'Schicht 1', start_time: '10:00', end_time: '14:00', max_participants: 1, required_skill_ids: [] }]
      }
    ]);
  };

  const removeTaskArea = (index) => {
    setTaskAreas(taskAreas.filter((_, i) => i !== index));
  };

  const updateTaskArea = (index, field, value) => {
    const updated = [...taskAreas];
    updated[index][field] = value;
    setTaskAreas(updated);
  };

  const addShift = (areaIndex) => {
    const updated = [...taskAreas];
    updated[areaIndex].shifts.push({
      title: `Schicht ${updated[areaIndex].shifts.length + 1}`,
      start_time: '14:00',
      end_time: '18:00',
      max_participants: 1,
      required_skill_ids: []
    });
    setTaskAreas(updated);
  };

  const removeShift = (areaIndex, shiftIndex) => {
    const updated = [...taskAreas];
    updated[areaIndex].shifts = updated[areaIndex].shifts.filter((_, i) => i !== shiftIndex);
    setTaskAreas(updated);
  };

  const updateShift = (areaIndex, shiftIndex, field, value) => {
    const updated = [...taskAreas];
    updated[areaIndex].shifts[shiftIndex][field] = value;
    setTaskAreas(updated);
  };

  const toggleShiftSkill = (areaIndex, shiftIndex, skillId) => {
    const updated = [...taskAreas];
    const currentSkills = updated[areaIndex].shifts[shiftIndex].required_skill_ids || [];
    if (currentSkills.includes(skillId)) {
      updated[areaIndex].shifts[shiftIndex].required_skill_ids = currentSkills.filter(id => id !== skillId);
    } else {
      updated[areaIndex].shifts[shiftIndex].required_skill_ids = [...currentSkills, skillId];
    }
    setTaskAreas(updated);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (!title.trim()) {
      setError('Bitte gib einen Veranstaltungstitel an.');
      return;
    }

    setSubmitting(true);
    try {
      await onSubmit({
        id: eventToEdit?.id,
        title,
        description,
        location,
        start_date: startDate,
        end_date: endDate,
        task_areas: taskAreas
      });
      onClose();
    } catch (err) {
      setError(err.message || 'Speichern der Veranstaltung fehlgeschlagen.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm overflow-y-auto font-sans">
      <div className="hallmark-panel w-full max-w-3xl rounded-sm border border-grid p-6 shadow-2xl relative my-8">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-muted hover:text-main rounded-sm transition"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-6 border-b border-grid pb-4">
          <div className="w-10 h-10 rounded-sm bg-blue-500/10 text-blue-500 border border-blue-500/20 flex items-center justify-center font-bold">
            {eventToEdit ? <Edit3 className="w-5 h-5" /> : <Calendar className="w-5 h-5" />}
          </div>
          <div>
            <h3 className="font-serif font-bold text-xl uppercase text-main">
              {eventToEdit ? 'Veranstaltung & Schichten bearbeiten' : 'Neue Veranstaltung erstellen'}
            </h3>
            <p className="text-xs text-muted font-mono">Definiere Titel, Datum, Aufgabenfelder, Schichten & Qualifikationen</p>
          </div>
        </div>

        {error && (
          <div className="mb-4 p-3 rounded-sm bg-red-500/10 border border-red-500/20 text-red-500 text-xs font-mono">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 font-mono text-xs">
            <div className="sm:col-span-2">
              <label className="block text-main mb-1 font-bold">Titel der Veranstaltung</label>
              <input
                type="text"
                required
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="z. B. Sommerfest 2026"
                className="w-full px-3 py-2 rounded-sm input-field text-xs"
              />
            </div>

            <div>
              <label className="block text-main mb-1 font-bold">Startdatum</label>
              <input
                type="date"
                required
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-3 py-2 rounded-sm input-field text-xs"
              />
            </div>

            <div>
              <label className="block text-main mb-1 font-bold">Enddatum</label>
              <input
                type="date"
                required
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-3 py-2 rounded-sm input-field text-xs"
              />
            </div>

            <div className="sm:col-span-2">
              <label className="block text-main mb-1 font-bold">Ort (optional)</label>
              <input
                type="text"
                value={location}
                onChange={(e) => setLocation(e.target.value)}
                placeholder="z. B. Vereinsheim, Großer Saal"
                className="w-full px-3 py-2 rounded-sm input-field text-xs"
              />
            </div>

            <div className="sm:col-span-2">
              <label className="block text-main mb-1 font-bold">Beschreibung (optional)</label>
              <textarea
                rows={2}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Details zur Veranstaltung..."
                className="w-full px-3 py-2 rounded-sm input-field text-xs"
              />
            </div>
          </div>

          {/* Task Areas & Shifts Section */}
          <div className="border-t border-grid pt-5 space-y-4 font-mono">
            <div className="flex items-center justify-between">
              <h4 className="font-serif font-bold text-base text-main flex items-center gap-2">
                <Layers className="w-4.5 h-4.5 text-blue-500" /> Aufgabenfelder & Schichten
              </h4>
              <button
                type="button"
                onClick={addTaskArea}
                className="px-3 py-1.5 rounded-sm text-xs font-mono font-bold bg-blue-500/10 text-blue-500 border border-blue-500/20 hover:bg-blue-500/20 transition flex items-center gap-1"
              >
                <Plus className="w-3.5 h-3.5" /> Bereich hinzufügen
              </button>
            </div>

            {taskAreas.map((area, aIdx) => (
              <div key={aIdx} className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <input
                    type="text"
                    required
                    placeholder="Name des Aufgabenfeldes (z. B. Tresendienst)"
                    value={area.name}
                    onChange={(e) => updateTaskArea(aIdx, 'name', e.target.value)}
                    className="flex-1 px-3 py-1.5 rounded-sm input-field text-xs font-bold"
                  />
                  <button
                    type="button"
                    onClick={() => removeTaskArea(aIdx)}
                    className="p-1.5 text-muted hover:text-red-400 transition"
                    title="Bereich entfernen"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>

                {/* Shifts inside this area */}
                <div className="pl-3 border-l-2 border-grid space-y-3">
                  <div className="flex items-center justify-between text-xs text-muted font-bold">
                    <span>Schichten & Zeitfenster</span>
                    <button
                      type="button"
                      onClick={() => addShift(aIdx)}
                      className="text-blue-500 hover:underline flex items-center gap-1"
                    >
                      <Plus className="w-3 h-3" /> Schicht hinzufügen
                    </button>
                  </div>

                  {area.shifts.map((shift, sIdx) => (
                    <div key={sIdx} className="p-3 rounded-sm bg-surface border border-grid space-y-2">
                      <div className="grid grid-cols-1 sm:grid-cols-12 gap-2 items-center text-xs">
                        <input
                          type="text"
                          placeholder="Titel"
                          value={shift.title}
                          onChange={(e) => updateShift(aIdx, sIdx, 'title', e.target.value)}
                          className="sm:col-span-4 px-2.5 py-1 rounded-sm input-field text-xs"
                        />
                        <input
                          type="text"
                          placeholder="Start (14:00)"
                          value={shift.start_time}
                          onChange={(e) => updateShift(aIdx, sIdx, 'start_time', e.target.value)}
                          className="sm:col-span-2 px-2.5 py-1 rounded-sm input-field text-xs"
                        />
                        <input
                          type="text"
                          placeholder="Ende (18:00)"
                          value={shift.end_time}
                          onChange={(e) => updateShift(aIdx, sIdx, 'end_time', e.target.value)}
                          className="sm:col-span-2 px-2.5 py-1 rounded-sm input-field text-xs"
                        />
                        <div className="sm:col-span-3 flex items-center gap-1">
                          <span className="text-[11px] text-muted">Plätze:</span>
                          <input
                            type="number"
                            min="1"
                            value={shift.max_participants}
                            onChange={(e) => updateShift(aIdx, sIdx, 'max_participants', parseInt(e.target.value) || 1)}
                            className="w-full px-2 py-1 rounded-sm input-field text-xs font-bold"
                          />
                        </div>
                        <button
                          type="button"
                          onClick={() => removeShift(aIdx, sIdx)}
                          className="sm:col-span-1 p-1 text-muted hover:text-red-400 text-center"
                          title="Schicht löschen"
                        >
                          <Trash2 className="w-3.5 h-3.5 mx-auto" />
                        </button>
                      </div>

                      {/* Required Skills selection */}
                      {skills && skills.length > 0 && (
                        <div className="pt-1.5 border-t border-grid text-[11px]">
                          <span className="text-muted block mb-1">Erforderliche Qualifikationen:</span>
                          <div className="flex flex-wrap gap-1.5">
                            {skills.map(sk => {
                              const isSelected = (shift.required_skill_ids || []).includes(sk.id);
                              return (
                                <button
                                  key={sk.id}
                                  type="button"
                                  onClick={() => toggleShiftSkill(aIdx, sIdx, sk.id)}
                                  style={{
                                    backgroundColor: isSelected ? sk.color : `${sk.color}15`,
                                    borderColor: sk.color,
                                    color: isSelected ? '#ffffff' : sk.color
                                  }}
                                  className="px-2 py-0.5 rounded-sm border text-[10px] font-bold transition"
                                >
                                  {sk.name} {isSelected ? '✓' : ''}
                                </button>
                              );
                            })}
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <div className="pt-4 flex justify-end gap-2 border-t border-grid font-mono">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-sm text-xs font-semibold text-muted hover:bg-surface-hover transition border border-grid"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={submitting}
              style={{ backgroundColor: 'var(--brand-primary)' }}
              className="px-5 py-2 rounded-sm text-xs font-bold text-white transition shadow-sm hover:brightness-110"
            >
              {submitting ? 'Speichern...' : eventToEdit ? 'Änderungen speichern' : 'Veranstaltung erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
