import React, { useState, useEffect, useCallback } from 'react';
import { X, Plus, GripVertical, Trash2, Pencil, FileText, ChevronLeft, Printer, Save, Search, Tag, ClipboardList } from 'lucide-react';
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd';
import { HybridBackend } from '../services/backend.ts';
import { ModeloReceita, ItemReceita, Especialidade, Paciente, Dentista } from '../types.ts';
import { useHybridBackend } from '../hooks/useHybridBackend.ts';
import { useToast } from '../contexts/ToastContext.tsx';

const VIAS = ['VO', 'SL', 'IV', 'IM', 'SC', 'Tópico', 'Inalatória', 'Colírio', 'Nasal'];
const FREQUENCIAS = ['1x/dia', '2x/dia', '3x/dia', '4x/dia', '6/6h', '8/8h', '12/12h', '24/24h', 'Dose única', 'Se necessário'];
const DURACOES = ['1 dia', '2 dias', '3 dias', '5 dias', '7 dias', '10 dias', '14 dias', '21 dias', '30 dias', 'Contínuo'];

const ITEM_VAZIO: Omit<ItemReceita, 'id' | 'ordem'> = { medicamento: '', dose: '', via: 'VO', frequencia: '8/8h', duracao: '7 dias', instrucoes: '' };

// --------------- Editor de item de medicamento ---------------
const ItemEditor: React.FC<{
    item: Omit<ItemReceita, 'id' | 'ordem'>;
    onChange: (v: Omit<ItemReceita, 'id' | 'ordem'>) => void;
    onSave: () => void;
    onCancel: () => void;
}> = ({ item, onChange, onSave, onCancel }) => {
    const inp = "w-full border border-gray-200 rounded-lg px-3 py-2 text-xs focus:ring-2 focus:ring-teal-100 focus:border-teal-300 outline-none bg-white";
    const sel = inp + " appearance-none";
    return (
        <div className="bg-teal-50 border border-teal-100 rounded-xl p-3 space-y-2">
            <div>
                <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Medicamento</label>
                <input autoFocus value={item.medicamento} onChange={e => onChange({ ...item, medicamento: e.target.value.toUpperCase() })}
                    placeholder="EX: AMOXICILINA 500MG" className={inp} />
            </div>
            <div className="grid grid-cols-2 gap-2">
                <div>
                    <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Dose</label>
                    <input value={item.dose} onChange={e => onChange({ ...item, dose: e.target.value })} placeholder="EX: 500mg" className={inp} />
                </div>
                <div>
                    <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Via</label>
                    <select value={item.via} onChange={e => onChange({ ...item, via: e.target.value })} className={sel}>
                        {VIAS.map(v => <option key={v}>{v}</option>)}
                    </select>
                </div>
            </div>
            <div className="grid grid-cols-2 gap-2">
                <div>
                    <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Frequência</label>
                    <select value={item.frequencia} onChange={e => onChange({ ...item, frequencia: e.target.value })} className={sel}>
                        {FREQUENCIAS.map(f => <option key={f}>{f}</option>)}
                    </select>
                </div>
                <div>
                    <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Duração</label>
                    <select value={item.duracao} onChange={e => onChange({ ...item, duracao: e.target.value })} className={sel}>
                        {DURACOES.map(d => <option key={d}>{d}</option>)}
                    </select>
                </div>
            </div>
            <div>
                <label className="text-[9px] font-black text-gray-500 uppercase tracking-wider">Instruções extras (opcional)</label>
                <input value={item.instrucoes || ''} onChange={e => onChange({ ...item, instrucoes: e.target.value })}
                    placeholder="EX: TOMAR APÓS AS REFEIÇÕES" className={inp} />
            </div>
            <div className="flex justify-end gap-2 pt-1">
                <button onClick={onCancel} className="px-3 py-1.5 bg-white border border-gray-200 text-gray-600 rounded-lg text-xs font-bold hover:bg-gray-50">Cancelar</button>
                <button onClick={onSave} disabled={!item.medicamento.trim()} className="px-3 py-1.5 bg-teal-600 text-white rounded-lg text-xs font-bold hover:bg-teal-700 disabled:opacity-40 flex items-center gap-1">
                    <Save size={12} /> Confirmar
                </button>
            </div>
        </div>
    );
};

// --------------- Editor de modelo ---------------
const ModeloEditor: React.FC<{
    modelo: ModeloReceita | null;
    especialidades: Especialidade[];
    onSave: (m: ModeloReceita) => void;
    onBack: () => void;
}> = ({ modelo, especialidades, onSave, onBack }) => {
    const toast = useToast();
    const [nome, setNome] = useState(modelo?.nome || '');
    const [espId, setEspId] = useState(modelo?.especialidadeId || '');
    const [instrucoes, setInstrucoes] = useState(modelo?.instrucoes || '');
    const [items, setItems] = useState<ItemReceita[]>(modelo?.items || []);
    const [editingIdx, setEditingIdx] = useState<number | null>(null);
    const [newItem, setNewItem] = useState<Omit<ItemReceita, 'id' | 'ordem'>>(ITEM_VAZIO);
    const [adding, setAdding] = useState(false);
    const [saving, setSaving] = useState(false);

    const espNome = especialidades.find(e => e.id === espId)?.nome || '';

    const onDragEnd = (result: DropResult) => {
        if (!result.destination) return;
        const list = [...items];
        const [moved] = list.splice(result.source.index, 1);
        list.splice(result.destination.index, 0, moved);
        setItems(list.map((it, i) => ({ ...it, ordem: i })));
    };

    const addItem = () => {
        if (!newItem.medicamento.trim()) return;
        setItems(prev => [...prev, { ...newItem, id: `new_${Date.now()}`, ordem: prev.length }]);
        setNewItem(ITEM_VAZIO);
        setAdding(false);
    };

    const updateItem = (idx: number, val: Omit<ItemReceita, 'id' | 'ordem'>) => {
        setItems(prev => prev.map((it, i) => i === idx ? { ...it, ...val } : it));
    };

    const removeItem = (idx: number) => setItems(prev => prev.filter((_, i) => i !== idx));

    const handleSave = async () => {
        if (!nome.trim()) { toast.error('NOME DO MODELO OBRIGATÓRIO'); return; }
        setSaving(true);
        try {
            const payload = { nome: nome.toUpperCase(), especialidadeId: espId || undefined, especialidadeNome: espNome || undefined, instrucoes: instrucoes || undefined, items };
            if (modelo?.id) {
                await HybridBackend.updateModeloReceita({ ...payload, id: modelo.id });
            } else {
                const res = await HybridBackend.saveModeloReceita(payload);
                onSave({ ...payload, id: res.id, items });
                return;
            }
            onSave({ ...payload, id: modelo.id, items });
        } catch { toast.error('ERRO AO SALVAR MODELO'); } finally { setSaving(false); }
    };

    const inp = "w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:ring-2 focus:ring-teal-100 focus:border-teal-300 outline-none bg-white";

    return (
        <div className="flex flex-col h-full">
            <div className="p-5 border-b border-gray-100 flex items-center gap-3">
                <button onClick={onBack} className="text-gray-400 hover:text-gray-700 flex-shrink-0"><ChevronLeft size={18} /></button>
                <h3 className="text-sm font-black text-gray-800 uppercase">{modelo ? 'Editar Modelo' : 'Novo Modelo'}</h3>
            </div>
            <div className="flex-1 overflow-y-auto p-5 space-y-4">
                <div>
                    <label className="block text-[10px] font-black text-gray-500 uppercase tracking-wider mb-1">Nome do Modelo *</label>
                    <input value={nome} onChange={e => setNome(e.target.value.toUpperCase())} className={inp} placeholder="EX: ANTIBIÓTICO PÓS-CIRÚRGICO" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="block text-[10px] font-black text-gray-500 uppercase tracking-wider mb-1">Especialidade</label>
                        <select value={espId} onChange={e => setEspId(e.target.value)} className={inp + " text-sm"}>
                            <option value="">— Geral —</option>
                            {especialidades.map(e => <option key={e.id} value={e.id}>{e.nome}</option>)}
                        </select>
                    </div>
                </div>
                <div>
                    <label className="block text-[10px] font-black text-gray-500 uppercase tracking-wider mb-1">Instrução Geral (opcional)</label>
                    <input value={instrucoes} onChange={e => setInstrucoes(e.target.value)} className={inp} placeholder="EX: USO EM CASO DE INFECÇÃO ODONTOGÊNICA" />
                </div>

                {/* Lista de medicamentos */}
                <div>
                    <div className="flex items-center justify-between mb-2">
                        <label className="text-[10px] font-black text-gray-500 uppercase tracking-wider">Medicamentos ({items.length})</label>
                        {!adding && <button onClick={() => setAdding(true)} className="flex items-center gap-1 text-xs font-bold text-teal-600 hover:text-teal-800">
                            <Plus size={13} /> Adicionar
                        </button>}
                    </div>

                    {adding && (
                        <div className="mb-2">
                            <ItemEditor item={newItem} onChange={setNewItem} onSave={addItem} onCancel={() => { setAdding(false); setNewItem(ITEM_VAZIO); }} />
                        </div>
                    )}

                    <DragDropContext onDragEnd={onDragEnd}>
                        <Droppable droppableId="items-receita">
                            {provided => (
                                <div ref={provided.innerRef} {...provided.droppableProps} className="space-y-1.5">
                                    {items.map((it, idx) => (
                                        <Draggable key={it.id} draggableId={it.id} index={idx}>
                                            {(prov, snap) => (
                                                <div ref={prov.innerRef} {...prov.draggableProps}
                                                    className={`rounded-xl border transition-shadow ${snap.isDragging ? 'shadow-lg border-teal-300 bg-teal-50' : 'border-gray-200 bg-white'}`}>
                                                    {editingIdx === idx ? (
                                                        <div className="p-2">
                                                            <ItemEditor
                                                                item={{ medicamento: it.medicamento, dose: it.dose, via: it.via, frequencia: it.frequencia, duracao: it.duracao, instrucoes: it.instrucoes }}
                                                                onChange={v => updateItem(idx, v)}
                                                                onSave={() => setEditingIdx(null)}
                                                                onCancel={() => setEditingIdx(null)}
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="flex items-center gap-2 px-3 py-2.5">
                                                            <span {...prov.dragHandleProps} className="text-gray-300 hover:text-gray-500 cursor-grab flex-shrink-0"><GripVertical size={15} /></span>
                                                            <div className="flex-1 min-w-0">
                                                                <p className="text-xs font-bold text-gray-800 uppercase truncate">{it.medicamento}</p>
                                                                <p className="text-[10px] text-gray-400">{[it.dose, it.via, it.frequencia, it.duracao].filter(Boolean).join(' · ')}</p>
                                                                {it.instrucoes && <p className="text-[10px] text-teal-500 italic">{it.instrucoes}</p>}
                                                            </div>
                                                            <button onClick={() => setEditingIdx(idx)} className="text-gray-300 hover:text-teal-500 flex-shrink-0"><Pencil size={13} /></button>
                                                            <button onClick={() => removeItem(idx)} className="text-gray-300 hover:text-red-500 flex-shrink-0"><Trash2 size={13} /></button>
                                                        </div>
                                                    )}
                                                </div>
                                            )}
                                        </Draggable>
                                    ))}
                                    {provided.placeholder}
                                    {items.length === 0 && !adding && (
                                        <div className="text-center py-6 text-xs text-gray-400 border-2 border-dashed border-gray-200 rounded-xl">
                                            Nenhum medicamento adicionado ainda
                                        </div>
                                    )}
                                </div>
                            )}
                        </Droppable>
                    </DragDropContext>
                </div>
            </div>
            <div className="p-4 border-t border-gray-100 flex justify-end gap-2">
                <button onClick={onBack} className="px-5 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold rounded-lg text-xs uppercase">Cancelar</button>
                <button onClick={handleSave} disabled={saving || !nome.trim()} className="px-5 py-2 bg-green-600 hover:bg-green-700 text-white font-bold rounded-lg text-xs uppercase flex items-center gap-1.5 disabled:opacity-40">
                    <Save size={14} /> {saving ? 'Salvando...' : 'Salvar Modelo'}
                </button>
            </div>
        </div>
    );
};

// --------------- Preview de impressão ---------------
const PrintPreview: React.FC<{
    modelo: ModeloReceita;
    paciente: Paciente;
    dentista?: Dentista;
    onClose: () => void;
}> = ({ modelo, paciente, dentista, onClose }) => {
    const hoje = new Date().toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' });
    return (
        <div className="flex flex-col h-full">
            <div className="p-4 border-b border-gray-100 flex items-center justify-between print:hidden">
                <div className="flex items-center gap-2">
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-700"><ChevronLeft size={18} /></button>
                    <h3 className="text-sm font-black text-gray-800 uppercase">Pré-visualização</h3>
                </div>
                <button onClick={() => window.print()} className="flex items-center gap-2 px-4 py-2 bg-gray-900 text-white rounded-lg text-xs font-bold hover:bg-black">
                    <Printer size={14} /> Imprimir / Salvar PDF
                </button>
            </div>
            <div className="flex-1 overflow-y-auto bg-gray-100 p-6 print:p-0 print:bg-white">
                <div id="receita-print" className="max-w-xl mx-auto bg-white rounded-2xl shadow-sm border border-gray-200 p-8 print:shadow-none print:rounded-none print:border-0 print:max-w-full">
                    <div className="text-center border-b-2 border-gray-800 pb-4 mb-6">
                        <h1 className="text-lg font-black text-gray-900 uppercase">RECEITUÁRIO</h1>
                        {dentista && <p className="text-sm font-bold text-gray-700 mt-1">{dentista.nome} — CRO: {dentista.cro || '—'}/{dentista.cro_uf || '—'}</p>}
                    </div>
                    <div className="mb-6 grid grid-cols-2 gap-3 text-sm">
                        <div><span className="text-gray-500 text-xs uppercase font-bold">Paciente</span><p className="font-bold text-gray-900 uppercase">{paciente.nome}</p></div>
                        <div><span className="text-gray-500 text-xs uppercase font-bold">Data</span><p className="font-bold text-gray-900">{hoje}</p></div>
                    </div>
                    {modelo.instrucoes && <div className="mb-5 p-3 bg-amber-50 border border-amber-200 rounded-lg text-xs text-amber-800 font-medium italic">{modelo.instrucoes}</div>}
                    <div className="space-y-4">
                        {modelo.items.map((it, i) => (
                            <div key={it.id} className="border-b border-gray-100 pb-3 last:border-0 last:pb-0">
                                <p className="font-black text-gray-900 text-sm">{i + 1}. {it.medicamento}</p>
                                <p className="text-gray-700 text-sm ml-4">
                                    {[it.dose, it.via, it.frequencia, `por ${it.duracao}`].filter(Boolean).join(' — ')}
                                </p>
                                {it.instrucoes && <p className="text-gray-500 text-xs ml-4 italic mt-0.5">{it.instrucoes}</p>}
                            </div>
                        ))}
                    </div>
                    <div className="mt-12 pt-6 border-t-2 border-gray-800 flex justify-between items-end">
                        <div><p className="text-xs text-gray-500">Assinatura e Carimbo</p><div className="h-10" /></div>
                        <p className="text-xs text-gray-400">{hoje}</p>
                    </div>
                </div>
            </div>
        </div>
    );
};

// --------------- Modal principal ---------------
export const ReceitaModal: React.FC<{ paciente: Paciente; onClose: () => void }> = ({ paciente, onClose }) => {
    const toast = useToast();
    const { data: especialidadesRaw } = useHybridBackend<Especialidade[]>(HybridBackend.getEspecialidades);
    const especialidades = especialidadesRaw ?? [];
    const { data: dentistasRaw } = useHybridBackend<Dentista[]>(HybridBackend.getDentistas);
    const dentistas = dentistasRaw ?? [];
    const [modelos, setModelos] = useState<ModeloReceita[]>([]);
    const [loading, setLoading] = useState(true);
    const [filtroEsp, setFiltroEsp] = useState('');
    const [busca, setBusca] = useState('');

    const [view, setView] = useState<'lista' | 'editor' | 'print'>('lista');
    const [modeloAtivo, setModeloAtivo] = useState<ModeloReceita | null>(null);
    const [printModelo, setPrintModelo] = useState<ModeloReceita | null>(null);

    const dentistaPrincipal = dentistas[0];

    const carregar = useCallback(async () => {
        setLoading(true);
        try { setModelos(await HybridBackend.getModelosReceita()); }
        catch { toast.error('Erro ao carregar modelos'); }
        finally { setLoading(false); }
    }, []);

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

    useEffect(() => {
        const h = (e: KeyboardEvent) => { if (e.key === 'Escape') { if (view !== 'lista') setView('lista'); else onClose(); } };
        document.addEventListener('keydown', h);
        return () => document.removeEventListener('keydown', h);
    }, [view, onClose]);

    const handleDelete = async (id: string) => {
        if (!confirm('Excluir este modelo?')) return;
        await HybridBackend.deleteModeloReceita(id);
        setModelos(prev => prev.filter(m => m.id !== id));
    };

    const filtrados = modelos.filter(m => {
        const matchEsp = !filtroEsp || m.especialidadeId === filtroEsp;
        const matchBusca = !busca || m.nome.toLowerCase().includes(busca.toLowerCase());
        return matchEsp && matchBusca;
    });

    return (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm p-0">
            <div className="bg-white shadow-2xl w-full h-dvh md:w-[96vw] md:h-[98vh] rounded-none md:rounded-2xl flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200">

                {view === 'lista' && (
                    <>
                        <div className="p-5 border-b border-gray-100 flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                <div className="w-8 h-8 bg-red-100 rounded-lg flex items-center justify-center"><FileText size={15} className="text-red-600" /></div>
                                <div>
                                    <h2 className="text-sm font-black text-gray-800 uppercase">Modelos de Receita</h2>
                                    <p className="text-[10px] text-gray-400 uppercase">{paciente.nome}</p>
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <button onClick={() => { setModeloAtivo(null); setView('editor'); }}
                                    className="flex items-center gap-1.5 px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-xs font-bold rounded-lg">
                                    <Plus size={13} /> Novo Modelo
                                </button>
                                <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X size={18} /></button>
                            </div>
                        </div>

                        <div className="flex flex-1 overflow-hidden">
                            {/* Sidebar especialidades */}
                            <div className="w-44 border-r border-gray-100 flex-shrink-0 overflow-y-auto bg-gray-50 p-2">
                                <p className="text-[9px] font-black text-gray-400 uppercase px-2 mb-2 tracking-wider">Especialidade</p>
                                <button onClick={() => setFiltroEsp('')}
                                    className={`w-full text-left px-2.5 py-1.5 rounded-lg text-xs font-bold mb-0.5 transition-colors ${!filtroEsp ? 'bg-teal-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}>
                                    Todas
                                </button>
                                {especialidades.map(e => (
                                    <button key={e.id} onClick={() => setFiltroEsp(e.id)}
                                        className={`w-full text-left px-2.5 py-1.5 rounded-lg text-xs font-bold mb-0.5 transition-colors truncate ${filtroEsp === e.id ? 'bg-teal-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}>
                                        {e.nome}
                                    </button>
                                ))}
                            </div>

                            {/* Lista de modelos */}
                            <div className="flex-1 flex flex-col overflow-hidden">
                                <div className="p-3 border-b border-gray-100">
                                    <div className="relative">
                                        <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400" />
                                        <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="Buscar modelo..."
                                            className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-xs focus:ring-2 focus:ring-teal-100 outline-none" />
                                    </div>
                                </div>
                                <div className="flex-1 overflow-y-auto p-3 space-y-2">
                                    {loading && <div className="text-center py-8 text-xs text-gray-400">Carregando...</div>}
                                    {!loading && filtrados.length === 0 && (
                                        <div className="text-center py-10">
                                            <ClipboardList size={28} className="text-gray-200 mx-auto mb-2" />
                                            <p className="text-xs text-gray-400">Nenhum modelo encontrado</p>
                                            <button onClick={() => { setModeloAtivo(null); setView('editor'); }}
                                                className="mt-3 text-xs font-bold text-teal-600 hover:underline">+ Criar primeiro modelo</button>
                                        </div>
                                    )}
                                    {filtrados.map(m => (
                                        <div key={m.id} className="bg-white border border-gray-200 rounded-xl p-3 hover:border-teal-200 hover:shadow-sm transition-all group">
                                            <div className="flex items-start justify-between gap-2">
                                                <div className="min-w-0 flex-1">
                                                    <p className="text-xs font-black text-gray-800 uppercase truncate">{m.nome}</p>
                                                    <div className="flex items-center gap-2 mt-0.5">
                                                        {m.especialidadeNome && <span className="text-[9px] bg-teal-50 text-teal-600 px-1.5 py-0.5 rounded-full font-bold uppercase">{m.especialidadeNome}</span>}
                                                        <span className="text-[9px] text-gray-400">{m.items.length} medicamento{m.items.length !== 1 ? 's' : ''}</span>
                                                    </div>
                                                    {m.instrucoes && <p className="text-[10px] text-gray-400 italic mt-1 truncate">{m.instrucoes}</p>}
                                                </div>
                                                <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
                                                    <button onClick={() => { setPrintModelo(m); setView('print'); }}
                                                        title="Prescrever para este paciente"
                                                        className="p-1.5 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-lg"><Printer size={13} /></button>
                                                    <button onClick={() => { setModeloAtivo(m); setView('editor'); }}
                                                        className="p-1.5 text-gray-400 hover:text-teal-600 hover:bg-teal-50 rounded-lg"><Pencil size={13} /></button>
                                                    <button onClick={() => handleDelete(m.id)}
                                                        className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 size={13} /></button>
                                                </div>
                                            </div>
                                            {m.items.length > 0 && (
                                                <div className="mt-2 pt-2 border-t border-gray-50 space-y-0.5">
                                                    {m.items.slice(0, 3).map(it => (
                                                        <p key={it.id} className="text-[10px] text-gray-500 truncate">
                                                            • {it.medicamento} — {it.dose} {it.frequencia}
                                                        </p>
                                                    ))}
                                                    {m.items.length > 3 && <p className="text-[10px] text-gray-400">+{m.items.length - 3} mais...</p>}
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </>
                )}

                {view === 'editor' && (
                    <ModeloEditor
                        modelo={modeloAtivo}
                        especialidades={especialidades}
                        onSave={m => { carregar(); setView('lista'); toast.success('MODELO SALVO!'); }}
                        onBack={() => setView('lista')}
                    />
                )}

                {view === 'print' && printModelo && (
                    <PrintPreview
                        modelo={printModelo}
                        paciente={paciente}
                        dentista={dentistaPrincipal}
                        onClose={() => setView('lista')}
                    />
                )}
            </div>
        </div>
    );
};
