/* Hallmark · pre-emit critique: P5 H5 E5 S5 R5 V5 */
/* Hallmark · component: EventEditorPage · genre: editorial · theme: Atelier (Dark & Light) · studied-DNA: https://inihaus.de */
import React, { useState, useEffect } from 'react';
import { ArrowLeft, Calendar, Layers, Plus, Trash2, Edit3, CheckCircle2, AlertCircle, Users, UserCheck } from 'lucide-react';
import { apiFetch } from '../api/client';

export default function EventEditorPage({ eventToEdit, skills, user, onBack, onSubmit, onDeleteEvent }) {
  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]);

  // Co-managers state
  const [coManagerIds, setCoManagerIds] = useState(
    eventToEdit?.co_managers ? eventToEdit.co_managers.map(u => u.id) : []
  );
  const [allUsers, setAllUsers] = useState([]);

  // Task areas state
  const [taskAreas, setTaskAreas] = useState([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchUsers();

    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,
          date: s.date || (eventToEdit ? eventToEdit.start_date : new Date().toISOString().split('T')[0]),
          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 fetchUsers = async () => {
    try {
      const data = await apiFetch('/users/all/');
      setAllUsers(data.results || data);
    } catch (e) {}
  };

  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}`,
      date: startDate,
      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 toggleSkillRequirement = (areaIndex, shiftIndex, skillId) => {
    const updated = [...taskAreas];
    const current = updated[areaIndex].shifts[shiftIndex].required_skill_ids || [];
    if (current.includes(skillId)) {
      updated[areaIndex].shifts[shiftIndex].required_skill_ids = current.filter(id => id !== skillId);
    } else {
      updated[areaIndex].shifts[shiftIndex].required_skill_ids = [...current, 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,
        co_manager_ids: coManagerIds,
        task_areas: taskAreas
      });
    } catch (err) {
      setError(err.message || 'Speichern der Veranstaltung fehlgeschlagen.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="space-y-6 max-w-4xl mx-auto animate-in fade-in duration-200 font-sans">
      {/* Navigation Header */}
      <div className="flex items-center justify-between font-mono text-xs">
        <button
          onClick={onBack}
          className="px-3.5 py-1.5 rounded-sm bg-subtle hover:bg-surface-hover text-main border border-grid transition flex items-center gap-2 font-bold"
        >
          <ArrowLeft className="w-4 h-4" /> [ ZURÜCK ZUR ÜBERSICHT ]
        </button>

        <span className="text-muted border border-grid px-2.5 py-0.5 rounded-sm">
          MODE: {eventToEdit ? 'EVENT EDIT' : 'NEW EVENT'}
        </span>
      </div>

      {/* Page Title Panel */}
      <div className="hallmark-panel rounded-sm p-6 sm:p-8 border border-grid space-y-2">
        <div className="flex items-center gap-3">
          <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>
            <h2 className="font-serif text-3xl font-bold uppercase tracking-tight text-main">
              {eventToEdit ? 'Veranstaltung & Schichten Bearbeiten' : 'Neue Veranstaltung Erstellen'}
            </h2>
            <p className="text-xs text-muted font-mono mt-0.5">
              Konfiguriere Stammdaten, Co-Verwalter, Aufgabenfelder, Schichtzeiten & Qualifikationen
            </p>
          </div>
        </div>
      </div>

      {error && (
        <div className="p-4 rounded-sm bg-red-500/10 border border-red-500/20 text-red-500 text-xs font-mono flex items-center gap-2">
          <AlertCircle className="w-4 h-4 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {/* Main Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Section 1: Stammdaten */}
        <div className="hallmark-panel rounded-sm p-6 border border-grid space-y-4 font-mono text-xs">
          <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
            1. Stammdaten & Verwalter der Veranstaltung
          </h3>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <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.5 py-2 rounded-sm input-field text-sm"
              />
            </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.5 py-2 rounded-sm input-field text-sm"
              />
            </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.5 py-2 rounded-sm input-field text-sm"
              />
            </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.5 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.5 py-2 rounded-sm input-field text-xs font-sans"
              />
            </div>

            {/* Co-Managers Selection */}
            {allUsers.length > 0 && (
              <div className="sm:col-span-2 pt-3 border-t border-grid space-y-2">
                <label className="block text-main font-bold flex items-center gap-1.5">
                  <Users className="w-4 h-4 text-indigo-400" /> Co-Verwalter / Mit-Organisatoren (optional)
                </label>
                <p className="text-[11px] text-muted font-sans">
                  Wähle registrierte Benutzer aus, die dieses Event ebenfalls verwalten, bearbeiten und Gäste eintragen dürfen:
                </p>
                <div className="flex flex-wrap gap-2 pt-1">
                  {allUsers.map((u) => {
                    const isSelected = coManagerIds.includes(u.id);
                    return (
                      <button
                        key={u.id}
                        type="button"
                        onClick={() => {
                          if (isSelected) {
                            setCoManagerIds(coManagerIds.filter(id => id !== u.id));
                          } else {
                            setCoManagerIds([...coManagerIds, u.id]);
                          }
                        }}
                        className={`px-3 py-1.5 rounded-sm text-xs font-mono font-bold transition flex items-center gap-1.5 border ${
                          isSelected
                            ? 'bg-indigo-500/20 text-indigo-300 border-indigo-500/50 shadow-sm'
                            : 'bg-subtle text-muted border-grid hover:text-main'
                        }`}
                      >
                        <UserCheck className={`w-3.5 h-3.5 ${isSelected ? 'text-indigo-400' : 'opacity-40'}`} />
                        <span>{u.display_name || u.username}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Section 2: Task Areas & Shifts */}
        <div className="hallmark-panel rounded-sm p-6 border border-grid space-y-4 font-mono text-xs">
          <div className="flex items-center justify-between border-b border-grid pb-2">
            <h3 className="font-serif text-lg font-bold uppercase text-main flex items-center gap-2">
              <Layers className="w-4 h-4 text-blue-500" /> 2. Aufgabenfelder & Schichten
            </h3>
            <button
              type="button"
              onClick={addTaskArea}
              className="px-3.5 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-3 px-2.5 py-1 rounded-sm input-field text-xs"
                      />
                      <input
                        type="date"
                        title="Schichtdatum"
                        min={startDate}
                        max={endDate}
                        value={shift.date || startDate}
                        onChange={(e) => updateShift(aIdx, sIdx, 'date', e.target.value)}
                        className="sm:col-span-3 px-2 py-1 rounded-sm input-field text-xs font-mono text-indigo-400 font-bold"
                      />
                      <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-1 flex items-center gap-1">
                        <input
                          type="number"
                          min="1"
                          title="Max. Plätze"
                          value={shift.max_participants}
                          onChange={(e) => updateShift(aIdx, sIdx, 'max_participants', parseInt(e.target.value) || 1)}
                          className="w-full px-1.5 py-1 rounded-sm input-field text-xs font-bold text-center"
                        />
                      </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>

                    {/* Skill requirements selector */}
                    {skills && skills.length > 0 && (
                      <div className="pt-2 border-t border-grid flex flex-wrap items-center gap-1.5">
                        <span className="text-[10px] text-muted font-bold mr-1">Erforderlich:</span>
                        {skills.map(sk => {
                          const isReq = (shift.required_skill_ids || []).includes(sk.id);
                          return (
                            <button
                              key={sk.id}
                              type="button"
                              onClick={() => toggleSkillRequirement(aIdx, sIdx, sk.id)}
                              style={{
                                backgroundColor: isReq ? `${sk.color}25` : 'transparent',
                                borderColor: isReq ? sk.color : 'var(--color-border-grid)',
                                color: isReq ? sk.color : 'var(--color-text-muted)'
                              }}
                              className="px-2 py-0.5 rounded-sm text-[10px] border font-bold transition flex items-center gap-1"
                            >
                              <span>{sk.name}</span>
                              {isReq && <CheckCircle2 className="w-3 h-3" />}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* Submit Actions */}
        <div className="flex items-center justify-between gap-3 pt-2 font-mono">
          {eventToEdit && onDeleteEvent && user && (user.is_admin_user || user.is_staff || user.is_superuser || eventToEdit.created_by === user.id || eventToEdit.created_by?.id === user.id) ? (
            <button
              type="button"
              onClick={() => onDeleteEvent(eventToEdit)}
              className="px-4 py-2.5 rounded-sm text-xs font-bold bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 transition flex items-center gap-1.5"
            >
              <Trash2 className="w-4 h-4" /> VERANSTALTUNG LÖSCHEN
            </button>
          ) : <div />}

          <div className="flex items-center gap-3">
            <button
              type="button"
              onClick={onBack}
              className="px-5 py-2.5 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-6 py-2.5 rounded-sm text-xs font-bold text-white transition hover:brightness-110 shadow-sm flex items-center gap-2"
            >
              <CheckCircle2 className="w-4 h-4" />
              {submitting ? 'Speichern...' : 'Veranstaltung Speichern'}
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
