import React, { useState, useEffect } from 'react';
import { X, Layers, Play, Plus, Trash2, CheckCircle2 } from 'lucide-react';
import { apiFetch } from '../api/client';

export default function TemplateModal({ onClose, onInstantiateTemplate }) {
  const [templates, setTemplates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState(null);

  // Form for instantiating template
  const [title, setTitle] = useState('');
  const [startDate, setStartDate] = useState(new Date().toISOString().split('T')[0]);
  const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);
  const [location, setLocation] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    fetchTemplates();
  }, []);

  const fetchTemplates = async () => {
    try {
      const data = await apiFetch('/templates/');
      setTemplates(data.results || data);
    } catch (err) {
      setError(err.message || 'Laden der Vorlagen fehlgeschlagen.');
    } finally {
      setLoading(false);
    }
  };

  const handleSelectTemplate = (template) => {
    setSelectedTemplate(template);
    setTitle(template.name);
  };

  const handleInstantiate = async (e) => {
    e.preventDefault();
    if (!selectedTemplate) return;

    setSubmitting(true);
    try {
      await onInstantiateTemplate(selectedTemplate.id, {
        title,
        start_date: startDate,
        end_date: endDate,
        location
      });
      onClose();
    } catch (err) {
      setError(err.message || 'Erstellen der Veranstaltung aus Vorlage fehlgeschlagen.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm overflow-y-auto">
      <div className="glass-panel w-full max-w-2xl rounded-2xl border border-slate-800 p-6 shadow-2xl relative my-8">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-slate-400 hover:text-white rounded-lg transition"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 rounded-xl bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 flex items-center justify-center">
            <Layers className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-bold text-lg text-white">Veranstaltungsvorlagen</h3>
            <p className="text-xs text-slate-400">Erstelle neue Veranstaltungen im Handumdrehen aus Vorlagen</p>
          </div>
        </div>

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

        {loading ? (
          <div className="text-center py-8 text-xs text-slate-400">Vorlagen laden...</div>
        ) : templates.length === 0 ? (
          <div className="text-center py-8 text-xs text-slate-500">
            Noch keine Vorlagen gespeichert. Du kannst eine bestehende Veranstaltung als Vorlage speichern.
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            {templates.map((tpl) => (
              <div
                key={tpl.id}
                onClick={() => handleSelectTemplate(tpl)}
                className={`p-4 rounded-xl border cursor-pointer transition ${
                  selectedTemplate?.id === tpl.id
                    ? 'bg-blue-600/10 border-blue-500 shadow-md shadow-blue-500/10'
                    : 'bg-slate-900/60 border-slate-800 hover:border-slate-700'
                }`}
              >
                <div className="flex items-center justify-between">
                  <h4 className="font-bold text-sm text-white">{tpl.name}</h4>
                  {selectedTemplate?.id === tpl.id && <CheckCircle2 className="w-4 h-4 text-blue-400" />}
                </div>
                {tpl.description && <p className="text-xs text-slate-400 mt-1">{tpl.description}</p>}
                <div className="text-[10px] text-slate-500 mt-2">
                  Erstellt von {tpl.created_by_name}
                </div>
              </div>
            ))}
          </div>
        )}

        {selectedTemplate && (
          <form onSubmit={handleInstantiate} className="border-t border-slate-800 pt-5 space-y-4">
            <h4 className="font-bold text-xs text-blue-400 uppercase tracking-wider">
              Veranstaltung aus "{selectedTemplate.name}" erstellen
            </h4>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="sm:col-span-2">
                <label className="block text-xs font-semibold text-slate-300 mb-1">Veranstaltungstitel</label>
                <input
                  type="text"
                  required
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  className="w-full px-3 py-2 rounded-xl bg-slate-900 border border-slate-800 text-white text-xs"
                />
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Startdatum</label>
                <input
                  type="date"
                  required
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-full px-3 py-2 rounded-xl bg-slate-900 border border-slate-800 text-white text-xs"
                />
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Enddatum</label>
                <input
                  type="date"
                  required
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-full px-3 py-2 rounded-xl bg-slate-900 border border-slate-800 text-white text-xs"
                />
              </div>
            </div>

            <div className="pt-2 flex justify-end gap-2">
              <button
                type="submit"
                disabled={submitting}
                className="px-5 py-2 rounded-xl text-xs font-bold bg-blue-600 hover:bg-blue-500 text-white transition flex items-center gap-1.5 shadow-lg shadow-blue-600/30"
              >
                <Play className="w-3.5 h-3.5" /> {submitting ? 'Erstellen...' : 'Veranstaltung jetzt erstellen'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
