import { useState, useEffect, useRef } from 'react';
import { PromotionService } from '../services/api';
import { Tag, Plus, Trash2, Edit3, ImagePlus, X, Save } from 'lucide-react';
import Modal from '../components/Modal';

export default function PromotionsPage() {
  const [promos, setPromos] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingPromo, setEditingPromo] = useState<any>(null);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Form State
  const [formData, setFormData] = useState({
    nome: '',
    descricao: '',
    preco_original: '',
    preco_promocional: '',
    imagem: '',
    ativo: true,
  });

  const fetchPromos = async () => {
    setLoading(true);
    const data = await PromotionService.list();
    setPromos(data);
    setLoading(false);
  };

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

  const handleOpenModal = (promo?: any) => {
    if (promo) {
      setEditingPromo(promo);
      setFormData({
        nome: promo.nome,
        descricao: promo.descricao || '',
        preco_original: promo.preco_original?.toString() || '',
        preco_promocional: promo.preco_promocional.toString(),
        imagem: promo.imagem || '',
        ativo: promo.ativo !== false,
      });
    } else {
      setEditingPromo(null);
      setFormData({ nome:'', descricao:'', preco_original:'', preco_promocional:'', imagem:'', ativo: true });
    }
    setIsModalOpen(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingPromo) {
        await PromotionService.update(editingPromo.id, formData);
      } else {
        await PromotionService.create(formData);
      }
      setIsModalOpen(false);
      fetchPromos();
    } catch (err) {
      alert('Erro ao salvar promoção');
    }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const body = new FormData();
      body.append('image', file);
      const res = await fetch('/api/promotions/upload', { method: 'POST', credentials: 'include', body });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Erro no upload');
      setFormData(f => ({ ...f, imagem: data.path }));
    } catch (err: any) {
      alert(err.message);
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (confirm('Tem certeza que deseja excluir esta promoção?')) {
      try {
        await PromotionService.delete(id);
        fetchPromos();
      } catch (err) {
        alert('Erro ao excluir');
      }
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header className="flex justify-between items-center">
        <div>
            <h2 className="text-3xl font-bold text-white tracking-tighter uppercase italic">Promoções</h2>
            <p className="text-slate-400 mt-1 font-medium">Produtos em oferta na landing page do Alemão.</p>
        </div>
        <button 
          onClick={() => handleOpenModal()}
          className="bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-black px-8 py-4 rounded-2xl flex items-center gap-2 transition-all shadow-lg shadow-emerald-500/20 active:scale-95 italic uppercase text-xs"
        >
            <Plus size={18} strokeWidth={3} />
            Nova Oferta
        </button>
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {loading ? (
            [1,2,3].map(i => (
                <div key={i} className="bg-slate-900/40 border border-slate-800 h-64 rounded-[2rem] animate-pulse" />
            ))
        ) : promos.map(promo => (
            <div key={promo.id} className="bg-slate-900/40 backdrop-blur-md border border-slate-800 rounded-[2rem] overflow-hidden hover:border-emerald-500/30 transition-all group flex flex-col relative">
                {promo.imagem ? (
                   <div className="h-40 w-full overflow-hidden relative">
                      <img src={promo.imagem} alt={promo.nome} className="w-full h-full object-cover opacity-60 group-hover:opacity-100 group-hover:scale-110 transition-all duration-700" />
                      <div className="absolute inset-0 bg-gradient-to-t from-slate-900 to-transparent" />
                   </div>
                ) : (
                    <div className="p-8">
                        <div className="p-4 bg-emerald-500/10 text-emerald-400 rounded-2xl w-fit border border-emerald-500/20">
                            <Tag size={24} />
                        </div>
                    </div>
                )}
                
                <div className="p-8 flex-1 flex flex-col">
                    <h3 className="text-xl font-black text-white mb-2 group-hover:text-emerald-400 transition-colors uppercase italic tracking-tight">
                        {promo.nome}
                    </h3>
                    <p className="text-slate-500 text-sm line-clamp-2 mb-8 font-medium italic">
                        {promo.descricao || 'Produto em destaque na vitrine.'}
                    </p>

                    <div className="mt-auto pt-8 border-t border-slate-800/50 flex items-center justify-between">
                        <div>
                            <span className="text-[10px] text-slate-500 font-black uppercase tracking-[0.2em] block mb-1">OFFER UNIT</span>
                            <div className="flex items-center gap-3">
                                {promo.preco_original && (
                                    <span className="text-slate-600 line-through text-xs font-bold tabular-nums">R$ {parseFloat(promo.preco_original).toFixed(2)}</span>
                                )}
                                <span className="text-emerald-400 font-black text-2xl tabular-nums italic tracking-tighter">R$ {parseFloat(promo.preco_promocional).toFixed(2)}</span>
                            </div>
                        </div>
                        
                        <div className="flex gap-3 relative z-10">
                            <button 
                              onClick={() => handleOpenModal(promo)}
                              className="p-3 bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700 rounded-xl transition-all border border-slate-700"
                            >
                                <Edit3 size={18} />
                            </button>
                            <button 
                              onClick={() => handleDelete(promo.id)}
                              className="p-3 bg-rose-500/10 text-rose-500 hover:bg-rose-500 hover:text-white rounded-xl transition-all border border-rose-500/10"
                            >
                                <Trash2 size={18} />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        ))}
      </div>

      {/* CRUD MODAL */}
      <Modal 
        isOpen={isModalOpen} 
        onClose={() => setIsModalOpen(false)} 
        title={editingPromo ? 'Editar Promoção' : 'Nova Promoção'}
      >
        <form onSubmit={handleSave} className="space-y-6">
            <div className="grid grid-cols-1 gap-6">
                <div>
                    <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Nome do Produto</label>
                    <input 
                        required
                        type="text" 
                        value={formData.nome}
                        onChange={e => setFormData({...formData, nome: e.target.value})}
                        className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-emerald-500 outline-none transition-all"
                        placeholder="Ex: Coca-Cola 2L"
                    />
                </div>
                <div>
                    <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Descrição</label>
                    <textarea 
                        value={formData.descricao}
                        onChange={e => setFormData({...formData, descricao: e.target.value})}
                        className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-emerald-500 outline-none transition-all h-24 resize-none"
                        placeholder="Breve descrição do produto..."
                    />
                </div>
                <div className="grid grid-cols-2 gap-4">
                    <div>
                        <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Preço Original</label>
                        <input 
                            type="number" step="0.01"
                            value={formData.preco_original}
                            onChange={e => setFormData({...formData, preco_original: e.target.value})}
                            className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-emerald-500 outline-none transition-all"
                            placeholder="0.00"
                        />
                    </div>
                    <div>
                        <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Preço Promo (Oferta)</label>
                        <input 
                            required
                            type="number" step="0.01"
                            value={formData.preco_promocional}
                            onChange={e => setFormData({...formData, preco_promocional: e.target.value})}
                            className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-emerald-500 outline-none transition-all"
                            placeholder="0.00"
                        />
                    </div>
                </div>
                <div>
                    <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Foto do Produto</label>
                    <input ref={fileInputRef} type="file" accept="image/*" onChange={handleImageUpload} className="hidden" />
                    {formData.imagem ? (
                        <div className="relative rounded-xl overflow-hidden border border-slate-700 h-40">
                            <img src={formData.imagem} alt="preview" className="w-full h-full object-cover" />
                            <button
                                type="button"
                                onClick={() => setFormData(f => ({ ...f, imagem: '' }))}
                                className="absolute top-2 right-2 p-1.5 bg-black/70 text-white rounded-lg hover:bg-rose-500 transition-all"
                            >
                                <X size={14} />
                            </button>
                        </div>
                    ) : (
                        <button
                            type="button"
                            onClick={() => fileInputRef.current?.click()}
                            disabled={uploading}
                            className="w-full h-32 border-2 border-dashed border-slate-700 hover:border-emerald-500/50 rounded-xl flex flex-col items-center justify-center gap-2 text-slate-500 hover:text-emerald-400 transition-all disabled:opacity-50"
                        >
                            <ImagePlus size={28} />
                            <span className="text-[11px] font-black uppercase tracking-widest">
                                {uploading ? 'Enviando...' : 'Clique para carregar foto'}
                            </span>
                        </button>
                    )}
                </div>
            </div>

            <button 
                type="submit"
                className="w-full bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-black py-4 rounded-2xl flex items-center justify-center gap-2 transition-all shadow-lg shadow-emerald-500/20 uppercase italic text-sm"
            >
                <Save size={20} />
                {editingPromo ? 'Salvar Alterações' : 'Criar Promoção'}
            </button>
        </form>
      </Modal>
    </div>
  );
}
