import {
  Save, Image, Star, Plus, Trash2, ArrowLeft, Upload, X
} from 'lucide-react';
import { Button } from '../../ui/Button';
import { ChangeEvent, useEffect, useState } from 'react';
import { useAppData } from '../../../context/AppDataContext';
import { saveEvent, uploadMedia } from '../../../services/api';

interface EventFormSectionProps {
  onCancel: () => void;
  eventId?: string | null;
}

interface BatchForm {
  id?: string;
  name: string;
  description?: string;
  price: number;
  ticketsPerUnit: number;
  quantity: number | '';
  sold: number;
  available: boolean;
  isUnlimited: boolean;
  status: 'active' | 'sold_out' | 'paused';
}

const emptyBatch = (): BatchForm => ({
  name: '',
  description: '',
  price: 0,
  ticketsPerUnit: 1,
  quantity: '',
  sold: 0,
  available: true,
  isUnlimited: false,
  status: 'active',
});

export function EventFormSection({ onCancel, eventId }: EventFormSectionProps) {
  const { events, reload } = useAppData();
  const editingEvent = events.find((event) => event.id === eventId);
  const [saving, setSaving] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);
  const [form, setForm] = useState({
    title: '',
    slug: '',
    description: '',
    date: '',
    horario: '',
    category: 'SHOW',
    location: 'Paraju / Domingos Martins - ES',
    attractionsText: '',
    imageUrl: '',
    status: 'draft' as 'active' | 'featured' | 'sold_out' | 'finished' | 'draft' | 'last_tickets',
    featured: false,
    totalTickets: 0,
    isUnlimited: false,
    internalNotes: '',
  });
  const [batches, setBatches] = useState<BatchForm[]>([emptyBatch()]);

  useEffect(() => {
    if (!editingEvent) {
      setForm({
        title: '',
        slug: '',
        description: '',
        date: '',
        horario: '',
        category: 'SHOW',
        location: 'Paraju / Domingos Martins - ES',
        attractionsText: '',
        imageUrl: '',
        status: 'draft',
        featured: false,
        totalTickets: 0,
        isUnlimited: false,
        internalNotes: '',
      });
      setBatches([emptyBatch()]);
      return;
    }

    setForm({
      title: editingEvent.title,
      slug: editingEvent.slug || '',
      description: editingEvent.description,
      date: editingEvent.date.toISOString().slice(0, 10),
      horario: editingEvent.horario || '',
      category: editingEvent.category || 'SHOW',
      location: editingEvent.location,
      attractionsText: editingEvent.attractions.join(', '),
      imageUrl: editingEvent.imageUrl,
      status: editingEvent.status,
      featured: Boolean(editingEvent.featured),
      totalTickets: editingEvent.totalTickets || 0,
      isUnlimited: Boolean(editingEvent.isUnlimited),
      internalNotes: editingEvent.internalNotes || '',
    });
    setBatches(editingEvent.batches.map((batch) => ({
      id: batch.id,
      name: batch.name,
      description: batch.description || '',
      price: batch.price,
      ticketsPerUnit: Math.max(1, batch.ticketsPerUnit || 1),
      quantity: batch.isUnlimited ? '' : (batch.quantity || 0),
      sold: batch.sold || 0,
      available: Boolean(batch.available),
      isUnlimited: Boolean(batch.isUnlimited),
      status: batch.status || 'active',
    })));
  }, [editingEvent]);

  const addBatch = () => setBatches((current) => [...current, emptyBatch()]);

  const removeBatch = (id?: string, index?: number) => {
    setBatches((current) => current.filter((batch, batchIndex) => batch.id !== id && batchIndex !== index));
  };

  const updateBatch = (index: number, field: keyof BatchForm, value: string | number | boolean) => {
    setBatches((current) =>
      current.map((batch, batchIndex) => batchIndex === index ? { ...batch, [field]: value } : batch),
    );
  };

  const handleImageUpload = async (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    event.target.value = '';
    if (!file) return;

    setUploadingImage(true);
    setImageError(null);

    try {
      const uploaded = await uploadMedia(file);
      setForm((current) => ({ ...current, imageUrl: uploaded.url }));
    } catch (requestError) {
      setImageError(requestError instanceof Error ? requestError.message : 'Não foi possível enviar a imagem.');
    } finally {
      setUploadingImage(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);

    try {
      await saveEvent({
        id: editingEvent?.id,
        ...form,
        attractionsText: form.attractionsText,
        batches: batches.filter((batch) => batch.name.trim() !== ''),
      });
      await reload();
      onCancel();
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : 'Não foi possível salvar o evento.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="max-w-5xl mx-auto space-y-10 pb-24 lg:pb-0">
      <div className="flex items-center gap-6">
        <button onClick={onCancel} className="w-12 h-12 rounded-2xl bg-white/5 flex items-center justify-center hover:bg-brand-wine hover:text-white transition-all">
          <ArrowLeft className="w-6 h-6" />
        </button>
        <div>
          <h2 className="text-4xl font-sans font-black text-white uppercase tracking-tighter leading-none">{editingEvent ? 'Editar Evento' : 'Novo Evento'}</h2>
          <p className="text-gray-500 text-[10px] font-black uppercase tracking-widest mt-1">Configure todas as informações do evento abaixo</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
        <div className="lg:col-span-8 space-y-8">
          <div className="p-8 sm:p-10 rounded-[40px] bg-white/[0.02] border border-white/5 space-y-8">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Nome do Evento</label>
                <input type="text" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="EX: BAILÃO DO GALPÃO IMPERIAL" className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none placeholder:text-gray-800" />
              </div>
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Slug (URL)</label>
                <input type="text" value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} placeholder="EX: almoco-imperial" className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none placeholder:text-gray-800" />
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Descrição</label>
              <textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="DETALHES SOBRE O EVENTO..." className="w-full h-40 bg-black/40 border border-white/5 rounded-3xl p-6 text-sm font-bold text-white focus:border-brand-wine transition-all outline-none resize-none placeholder:text-gray-800" />
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-4 gap-6">
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Data</label>
                <input type="date" value={form.date} onChange={(e) => setForm({ ...form, date: e.target.value })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none" />
              </div>
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Horário</label>
                <input type="time" value={form.horario} onChange={(e) => setForm({ ...form, horario: e.target.value })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none" />
              </div>
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Categoria</label>
                <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none appearance-none">
                  <option>SHOW</option>
                  <option>MÚSICA</option>
                  <option>CULTURA</option>
                  <option>LAZER</option>
                </select>
              </div>
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Limite Total</label>
                <input type="number" disabled={form.isUnlimited} value={form.isUnlimited ? '' : form.totalTickets} onChange={(e) => setForm({ ...form, totalTickets: Number(e.target.value) })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none disabled:opacity-40" />
              </div>
            </div>

            <label className="flex items-center gap-4 p-4 rounded-2xl bg-white/[0.02] border border-white/5 cursor-pointer">
              <input type="checkbox" checked={form.isUnlimited} onChange={(e) => setForm({ ...form, isUnlimited: e.target.checked, totalTickets: e.target.checked ? 0 : form.totalTickets })} className="w-6 h-6 rounded-lg accent-brand-wine" />
              <div className="flex flex-col">
                <span className="text-[10px] font-black text-white uppercase tracking-widest">Evento com ingressos ilimitados</span>
                <span className="text-[8px] text-gray-600 font-bold uppercase tracking-widest">Quando ativo, o limite total fica livre</span>
              </div>
            </label>

            <div className="space-y-2">
              <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Local</label>
              <input type="text" value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none" />
            </div>

            <div className="space-y-2">
              <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Atrações (Separadas por vírgula)</label>
              <input type="text" value={form.attractionsText} onChange={(e) => setForm({ ...form, attractionsText: e.target.value })} placeholder="EX: NEGUINHO SAFADÃO, DJ X..." className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none placeholder:text-gray-800" />
            </div>
          </div>

          <div className="space-y-6">
            <div className="flex items-center justify-between px-2">
              <h3 className="text-xl font-sans font-black text-white uppercase tracking-tighter">Lotes de Ingressos</h3>
              <Button onClick={addBatch} variant="outline" size="sm" className="rounded-xl border-white/10 gap-2 text-[8px] font-black tracking-widest py-3">
                <Plus className="w-3 h-3" /> ADICIONAR LOTE
              </Button>
            </div>

            <div className="space-y-4">
              {batches.map((batch, index) => (
                <div key={batch.id || index} className="p-6 rounded-[32px] bg-white/[0.02] border border-white/5 flex flex-col gap-6 relative group">
                  <button onClick={() => removeBatch(batch.id, index)} className="absolute top-4 right-4 text-gray-700 hover:text-red-500 transition-colors">
                    <Trash2 className="w-4 h-4" />
                  </button>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Nome do Lote</label>
                      <input type="text" value={batch.name} onChange={(e) => updateBatch(index, 'name', e.target.value)} placeholder="EX: PROMOCIONAL" className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Descrição</label>
                      <input type="text" value={batch.description} onChange={(e) => updateBatch(index, 'description', e.target.value)} placeholder="LOTE VIGENTE" className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all" />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 sm:grid-cols-5 gap-6">
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Preço (R$)</label>
                      <input type="number" value={batch.price} onChange={(e) => updateBatch(index, 'price', Number(e.target.value))} className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">QR por unidade</label>
                      <input type="number" min={1} max={20} value={batch.ticketsPerUnit} onChange={(e) => updateBatch(index, 'ticketsPerUnit', Math.max(1, Number(e.target.value) || 1))} className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Qtd</label>
                      <input type="number" disabled={batch.isUnlimited} value={batch.isUnlimited ? '' : batch.quantity} onChange={(e) => updateBatch(index, 'quantity', Number(e.target.value))} className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all disabled:opacity-40" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Vendidos</label>
                      <input type="number" value={batch.sold} onChange={(e) => updateBatch(index, 'sold', Number(e.target.value))} className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all" />
                    </div>
                    <div className="space-y-2">
                      <label className="text-[9px] text-gray-600 font-black uppercase tracking-widest px-2">Status</label>
                      <select value={batch.status} onChange={(e) => updateBatch(index, 'status', e.target.value as BatchForm['status'])} className="w-full h-12 bg-black/40 border border-white/5 rounded-xl px-4 text-xs font-black text-white focus:border-brand-wine transition-all appearance-none">
                        <option value="active">ATIVO</option>
                        <option value="sold_out">ESGOTADO</option>
                        <option value="paused">PAUSADO</option>
                      </select>
                    </div>
                  </div>
                  <label className="flex items-center gap-3 p-3 rounded-2xl bg-black/30 border border-white/5 cursor-pointer">
                    <input type="checkbox" checked={batch.isUnlimited} onChange={(e) => updateBatch(index, 'isUnlimited', e.target.checked)} className="w-5 h-5 rounded accent-brand-wine" />
                    <span className="text-[9px] font-black uppercase tracking-widest text-white">Lote ilimitado</span>
                  </label>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="lg:col-span-4 space-y-8">
          <div className="p-8 rounded-[40px] bg-white/[0.02] border border-white/5 space-y-8">
            <div className="space-y-4">
              <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2 block">Imagem de Capa</label>
              <label className="aspect-[4/5] bg-black/40 rounded-[32px] border-2 border-dashed border-white/5 hover:border-brand-gold/40 flex flex-col items-center justify-center gap-4 overflow-hidden relative group cursor-pointer transition-all">
                <input type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={(event) => void handleImageUpload(event)} disabled={uploadingImage} />
                {form.imageUrl ? (
                  <>
                    <img src={form.imageUrl} alt={form.title || 'Evento'} className="w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/55 transition-all flex items-center justify-center opacity-0 group-hover:opacity-100">
                      <div className="flex items-center gap-2 rounded-2xl bg-black/80 border border-white/10 px-5 py-3 text-[9px] font-black uppercase tracking-widest text-white">
                        <Upload className="w-4 h-4 text-brand-gold" />
                        Trocar imagem
                      </div>
                    </div>
                  </>
                ) : (
                  <div className="flex flex-col items-center gap-2 group-hover:scale-110 transition-transform">
                    {uploadingImage ? (
                      <>
                        <div className="h-10 w-10 rounded-full border-2 border-brand-gold/20 border-t-brand-gold animate-spin" />
                        <span className="text-[9px] font-black text-brand-gold uppercase tracking-widest">Enviando imagem...</span>
                      </>
                    ) : (
                      <>
                        <Image className="w-10 h-10 text-gray-700" />
                        <span className="text-[9px] font-black text-gray-600 uppercase tracking-widest text-center">Clique para enviar imagem</span>
                        <span className="text-[8px] font-black text-gray-700 uppercase tracking-widest">ou cole a URL abaixo</span>
                      </>
                    )}
                  </div>
                )}
              </label>
              <div className="flex gap-3">
                <input type="text" value={form.imageUrl} onChange={(e) => setForm({ ...form, imageUrl: e.target.value })} placeholder="https://... ou /uploads/imagem.jpg" className="min-w-0 flex-1 rounded-2xl h-14 bg-black/40 border border-white/10 px-5 text-[10px] font-black tracking-widest text-white" />
                {form.imageUrl && (
                  <button type="button" onClick={() => setForm({ ...form, imageUrl: '' })} className="h-14 w-14 rounded-2xl border border-white/10 bg-black/40 flex items-center justify-center text-gray-500 hover:text-white hover:border-brand-gold/40 transition-all" title="Remover imagem">
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              <Button variant="outline" className="w-full rounded-2xl h-12 text-[9px] font-black tracking-[0.2em] gap-2" disabled={uploadingImage} onClick={() => document.getElementById('event-cover-upload')?.click()}>
                <Upload className="w-4 h-4" /> {uploadingImage ? 'ENVIANDO...' : 'FAZER UPLOAD'}
              </Button>
              <input id="event-cover-upload" type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={(event) => void handleImageUpload(event)} disabled={uploadingImage} />
              {imageError && <p className="text-[9px] uppercase tracking-[0.2em] font-black text-red-400 px-2">{imageError}</p>}
            </div>

            <div className="pt-8 border-t border-white/5 space-y-6">
              <div className="space-y-2">
                <label className="text-[10px] text-gray-500 font-black uppercase tracking-widest px-2">Status do Evento</label>
                <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value as typeof form.status })} className="w-full h-16 bg-black/40 border border-white/5 rounded-2xl px-6 text-sm font-black text-white focus:border-brand-wine transition-all outline-none appearance-none">
                  <option value="active">ATIVO</option>
                  <option value="featured">EM DESTAQUE</option>
                  <option value="sold_out">ESGOTADO</option>
                  <option value="finished">ENCERRADO</option>
                  <option value="draft">RASCUNHO</option>
                </select>
              </div>

              <label className="flex items-center gap-4 p-4 rounded-2xl bg-white/[0.02] border border-white/5 cursor-pointer">
                <input type="checkbox" checked={form.featured} onChange={(e) => setForm({ ...form, featured: e.target.checked })} className="w-6 h-6 rounded-lg accent-brand-wine" />
                <div className="flex flex-col">
                  <span className="text-[10px] font-black text-white uppercase tracking-widest">Evento em Destaque</span>
                  <span className="text-[8px] text-gray-600 font-bold uppercase tracking-widest">EXIBIR NO TOPO DA HOME</span>
                </div>
              </label>
            </div>
          </div>

          <div className="p-8 rounded-[40px] bg-brand-gold/5 border border-brand-gold/10 space-y-6">
            <h4 className="text-[10px] text-brand-gold font-black uppercase tracking-[0.3em] px-2 flex items-center gap-2">
              <Star className="w-4 h-4" /> Notas Internas
            </h4>
            <textarea value={form.internalNotes} onChange={(e) => setForm({ ...form, internalNotes: e.target.value })} placeholder="OBSERVAÇÕES EXCLUSIVAS DO ADMIN..." className="w-full h-40 bg-black/40 border border-brand-gold/10 rounded-2xl p-4 text-xs font-bold text-white focus:border-brand-gold transition-all outline-none resize-none placeholder:text-gray-800" />
            {error && <p className="text-[10px] uppercase tracking-[0.2em] font-black text-red-400">{error}</p>}
            <Button variant="primary" className="w-full rounded-2xl h-16 text-xs font-black tracking-[0.2em] shadow-xl shadow-brand-wine/20" onClick={() => void handleSave()} disabled={saving}>
              <Save className="w-5 h-5 mr-3" /> {saving ? 'SALVANDO...' : 'SALVAR EVENTO'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
