import React, { useState, useEffect, useMemo } from 'react';
import {
    Users,
    Trash2,
    Check,
    AlertCircle,
    PlusCircle,
    Camera,
    Stethoscope,
    ChevronRight,
    ChevronLeft,
    Search,
    X
} from 'lucide-react';
import { PageHeader } from '../components/PageHeader.tsx';
import { HybridBackend } from '../services/backend.ts';
import { Paciente, Dentista, Procedimento, Especialidade } from '../types.ts';
import { useToast } from '../contexts/ToastContext.tsx';
import { create } from 'zustand';

// --- STORES ---
interface GTOItem {
    id: string;
    procedimentoId: string;
    codigoTUSS: string;
    codigoInterno: string;
    descricao: string;
    dente?: string;
    face?: string;
    arco?: string;
    quantidade: number;
    valorUnitario: number;
    valorTotal: number;
    observacao?: string;
    // Prótese (Fase 1): item ligado ao catálogo do protético → gera OS ao finalizar.
    produtoId?: string;
    proteticoId?: string;
}

interface GTOStore {
    paciente: Paciente | null;
    dentista: Dentista | null;
    credenciada: string;
    items: GTOItem[];
    pendingSearch: string;
    setPaciente: (p: Paciente | null) => void;
    setDentista: (d: Dentista | null) => void;
    setCredenciada: (c: string) => void;
    addItem: (item: GTOItem) => void;
    removeItem: (id: string) => void;
    updateItem: (id: string, update: Partial<Pick<GTOItem, 'face' | 'observacao'>>) => void;
    clear: () => void;
    setPendingSearch: (s: string) => void;
}

const useGTOStore = create<GTOStore>((set) => ({
    paciente: null,
    dentista: null,
    credenciada: '',
    items: [],
    pendingSearch: '',
    setPaciente: (paciente) => set({ paciente }),
    setDentista: (dentista) => set({ dentista }),
    setCredenciada: (credenciada) => set({ credenciada }),
    addItem: (item) => set((state) => ({
        items: [...state.items, item].slice(0, 20)
    })),
    removeItem: (id) => set((state) => ({
        items: state.items.filter(i => i.id !== id)
    })),
    updateItem: (id, update) => set((state) => ({
        items: state.items.map(i => i.id === id ? { ...i, ...update } : i)
    })),
    clear: () => set({ paciente: null, dentista: null, items: [] }),
    setPendingSearch: (pendingSearch) => set({ pendingSearch }),
}));

export { useGTOStore };

// --- ODONTOGRAM DATA ---
const DENTES_ADULTO = {
    q1: [14, 13, 12, 11, 18, 17, 16, 15],
    q2: [21, 22, 23, 24, 25, 26, 27, 28],
    q4: [44, 43, 42, 41, 48, 47, 46, 45],
    q3: [31, 32, 33, 34, 35, 36, 37, 38],
    extras: { q1: 19, q2: 29, q4: 49, q3: 39 }
};

const DENTES_CRIANCA = {
    q1: [null, 53, 52, 51, null, null, 55, 54],
    q2: [61, 62, 63, null, 64, 65, null, null],
    q4: [null, 83, 82, 81, null, null, 85, 84],
    q3: [71, 72, 73, null, 74, 75, null, null]
};

const FACES = ['O', 'M', 'D', 'V', 'L', 'P'];

const normalize = (s: string) =>
    s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();

// --- COMPONENT ---
export const LancarGTO: React.FC = () => {
    const store = useGTOStore();
    const toast = useToast();

    const [pacientes, setPacientes] = useState<Paciente[]>([]);
    const [dentistas, setDentistas] = useState<Dentista[]>([]);
    const [especialidades, setEspecialidades] = useState<Especialidade[]>([]);
    const [procedimentos, setProcedimentos] = useState<Procedimento[]>([]);
    const [convenios, setConvenios] = useState<any[]>([]);

    const [selectedEsp, setSelectedEsp] = useState<string>('');
    const [selectedProc, setSelectedProc] = useState<Procedimento | null>(null);
    const [pacienteTipo, setPacienteTipo] = useState<'ADULTO' | 'CRIANCA'>('ADULTO');
    const [showMixed, setShowMixed] = useState(false);
    const [selectedDentes, setSelectedDentes] = useState<string[]>([]);
    const [selectedArco, setSelectedArco] = useState<'AI' | 'AS' | null>(null);
    const [arcoFace, setArcoFace] = useState('');
    const [arcoObs, setArcoObs] = useState('');

    const [mobilePage, setMobilePage] = useState<1 | 2 | 3>(1);
    const [patientSearchOpen, setPatientSearchOpen] = useState(false);
    const [patientSearchTerm, setPatientSearchTerm] = useState('');

    // --- PRÓTESE (Fase 1): catálogo do protético entra como "procedimentos" do GTO ---
    const [laboratorios, setLaboratorios] = useState<any[]>([]);
    const [selectedLab, setSelectedLab] = useState<string>('');
    const [labProdutos, setLabProdutos] = useState<any[]>([]);
    const [selectedProdutoId, setSelectedProdutoId] = useState<string>('');
    const [protValor, setProtValor] = useState<string>('');
    const [protObs, setProtObs] = useState<string>('');

    useEffect(() => {
        const load = async () => {
            const p = await HybridBackend.getPacientes();
            const d = await HybridBackend.getDentistas();
            const es = await HybridBackend.getEspecialidades();
            const pr = await HybridBackend.getProcedimentos();
            const cv = await HybridBackend.getPlanos();
            setPacientes(Array.isArray(p) ? p : (p?.data ?? []));
            setDentistas(d ?? []);
            setEspecialidades(es ?? []);
            setProcedimentos(pr ?? []);
            setConvenios(Array.isArray(cv) ? cv : []);
        };
        load();
    }, []);

    const filteredProcedimentos = useMemo(() => {
        if (!selectedEsp) return [];
        return procedimentos.filter(p => p.especialidadeId === selectedEsp);
    }, [selectedEsp, procedimentos]);

    // Especialidade de prótese → o "procedimento" vem do catálogo do protético (não da
    // tabela procedimentos). Detecta pela área da especialidade (re-tagueada no backend).
    const isProtese = useMemo(
        () => (especialidades.find(e => e.id === selectedEsp)?.area || '') === 'protese',
        [especialidades, selectedEsp]
    );
    const selectedProduto = useMemo(
        () => labProdutos.find(p => p.id === selectedProdutoId) || null,
        [labProdutos, selectedProdutoId]
    );

    // Carrega os laboratórios acessíveis assim que a especialidade de prótese é escolhida.
    useEffect(() => {
        if (!isProtese || laboratorios.length) return;
        HybridBackend.getProteseLaboratorios().then(l => setLaboratorios(Array.isArray(l) ? l : [])).catch(() => {});
    }, [isProtese, laboratorios.length]);

    // Catálogo do laboratório selecionado.
    useEffect(() => {
        if (!selectedLab) { setLabProdutos([]); return; }
        let active = true;
        HybridBackend.getLaboratorioProdutos(selectedLab)
            .then(p => { if (active) setLabProdutos(Array.isArray(p) ? p : []); })
            .catch(() => { if (active) setLabProdutos([]); });
        return () => { active = false; };
    }, [selectedLab]);

    // Busca de pacientes é SERVER-SIDE: a clínica pode ter milhares e a rota sem termo
    // devolve só as 50 primeiras. Filtrar essas 50 no cliente fazia a busca "não achar"
    // quem estava fora da 1ª página. Sem termo, mostra a lista inicial (recentes).
    const [patientResults, setPatientResults] = useState<Paciente[]>([]);
    const [searchingPatients, setSearchingPatients] = useState(false);

    useEffect(() => {
        const term = patientSearchTerm.trim();
        if (!term) { setPatientResults(pacientes.slice(0, 30)); setSearchingPatients(false); return; }
        let active = true;
        setSearchingPatients(true);
        const t = setTimeout(async () => {
            try {
                const r: any = await HybridBackend.getPacientes(term);
                const list: Paciente[] = Array.isArray(r) ? r : (r?.data ?? []);
                if (active) setPatientResults(list);
            } finally {
                if (active) setSearchingPatients(false);
            }
        }, 300);
        return () => { active = false; clearTimeout(t); };
    }, [patientSearchTerm, pacientes]);

    useEffect(() => {
        const { pendingSearch } = store;
        if (!pendingSearch || pacientes.length === 0) return;
        const term = normalize(pendingSearch);
        const matches = pacientes.filter(p => {
            const n = normalize(p.nome);
            return n === term || n.includes(term) || term.includes(n);
        });
        if (matches.length === 1) {
            store.setPaciente(matches[0]);
        } else if (matches.length > 1) {
            setPatientSearchTerm(pendingSearch);
            setPatientSearchOpen(true);
        } else {
            setPatientSearchOpen(true);
        }
        store.setPendingSearch('');
    }, [pacientes, store.pendingSearch]); // eslint-disable-line react-hooks/exhaustive-deps

    // Tooth click → immediate add/remove from store
    const toggleDente = (num: string) => {
        if (!selectedProc) {
            toast.error("SELECIONE UM PROCEDIMENTO ANTES DE ESCOLHER O DENTE.");
            return;
        }
        if (selectedProc.tipo_regiao !== 'DENTE') {
            toast.error("ESTE PROCEDIMENTO NÃO PERMITE SELEÇÃO DE DENTE INDIVIDUAL.");
            return;
        }

        const existingItem = store.items.find(
            i => i.dente === num && i.procedimentoId === selectedProc.id
        );

        if (existingItem) {
            store.removeItem(existingItem.id);
            setSelectedDentes(prev => prev.filter(d => d !== num));
        } else {
            if (store.items.length >= 20) {
                toast.error("LIMITE DE 20 ITENS ATINGIDO.");
                return;
            }
            store.addItem({
                id: Math.random().toString(36).substring(7),
                procedimentoId: selectedProc.id,
                codigoTUSS: selectedProc.codigo || '000000',
                codigoInterno: selectedProc.codigoInterno || '',
                descricao: selectedProc.descricao_mobile || selectedProc.nome,
                dente: num,
                face: '',
                quantidade: 1,
                valorUnitario: selectedProc.valorParticular || 0,
                valorTotal: selectedProc.valorParticular || 0,
            });
            setSelectedDentes(prev => [...prev, num]);
            setSelectedArco(null);
        }
    };

    const selectArco = (arco: 'AI' | 'AS') => {
        if (selectedProc?.tipo_regiao !== 'ARCO') {
            toast.error("ESTE PROCEDIMENTO NÃO PERMITE SELEÇÃO DE ARCO.");
            return;
        }
        setSelectedDentes([]);
        setSelectedArco(arco);
    };

    // Only used for ARCO / GERAL procedures
    const handleAddItem = () => {
        if (!selectedProc) {
            toast.error("SELECIONE UM PROCEDIMENTO PRIMEIRO.");
            return;
        }
        if (selectedProc.tipo_regiao === 'ARCO' && !selectedArco) {
            toast.error("SELECIONE UM ARCO (AI/AS).");
            return;
        }
        if (selectedProc.exige_face && !arcoFace.trim()) {
            toast.error("A FACE É OBRIGATÓRIA PARA ESTE PROCEDIMENTO.");
            return;
        }
        store.addItem({
            id: Math.random().toString(36).substring(7),
            procedimentoId: selectedProc.id,
            codigoTUSS: selectedProc.codigo || '000000',
            codigoInterno: selectedProc.codigoInterno || '',
            descricao: selectedProc.nome,
            arco: selectedArco || undefined,
            face: arcoFace,
            quantidade: 1,
            valorUnitario: selectedProc.valorParticular || 0,
            valorTotal: selectedProc.valorParticular || 0,
            observacao: arcoObs || undefined,
        });
        toast.success("ADICIONADO AO RASCUNHO.");
        setSelectedArco(null);
        setArcoFace('');
        setArcoObs('');
    };

    // Adiciona um item de prótese (catálogo do protético) ao rascunho do GTO.
    const handleAddProtese = () => {
        if (!selectedLab) { toast.error("SELECIONE O LABORATÓRIO."); return; }
        if (!selectedProduto) { toast.error("SELECIONE O PRODUTO DE PRÓTESE."); return; }
        if (store.items.length >= 20) { toast.error("LIMITE DE 20 ITENS ATINGIDO."); return; }
        const valor = parseFloat(protValor) || Number(selectedProduto.preco) || 0;
        store.addItem({
            id: Math.random().toString(36).substring(7),
            procedimentoId: '',
            codigoTUSS: '',
            codigoInterno: '',
            descricao: selectedProduto.nome,
            quantidade: 1,
            valorUnitario: valor,
            valorTotal: valor,
            observacao: protObs || undefined,
            produtoId: selectedProduto.id,
            proteticoId: selectedLab,
        });
        toast.success("PRÓTESE ADICIONADA AO RASCUNHO.");
        setSelectedProdutoId('');
        setProtValor('');
        setProtObs('');
    };

    const handleFinalize = async () => {
        if (!store.paciente || !store.dentista || store.items.length === 0) {
            toast.error("PACIENTE, DENTISTA E PELO MENOS 1 ITEM SÃO OBRIGATÓRIOS.");
            return;
        }
        if (!store.credenciada) {
            toast.error("SELECIONE O CONVÊNIO / CREDENCIADA.");
            return;
        }
        const semFace = store.items.filter(i => {
            if (!i.dente) return false;
            const proc = procedimentos.find(p => p.id === i.procedimentoId);
            return proc?.exige_face && !i.face;
        });
        if (semFace.length > 0) {
            toast.error(`FACE OBRIGATÓRIA PARA ${semFace.map(i => `DENTE ${i.dente}`).join(', ')}`);
            return;
        }
        try {
            // Persiste a GTO e finaliza → gera o lançamento (convênio a receber) no Financeiro
            const { id } = await HybridBackend.createGtoBuilder({
                pacienteId: store.paciente.id,
                dentistaId: store.dentista.id,
                credenciadaId: store.credenciada,
            });
            for (const it of store.items) {
                const { arco, id: _localId, produtoId, proteticoId, ...rest } = it as any;
                void arco; void _localId;
                const payload: any = { ...rest };
                // Prótese: envia produto/protético (snake_case) → o backend abre a OS na finalização.
                if (produtoId) { payload.produto_id = produtoId; payload.protetico_id = proteticoId; }
                await HybridBackend.addGtoItem(id, payload);
            }
            const fin = await HybridBackend.finalizarGto(id);
            toast.success(fin?.financeiro_id
                ? `GTO GERADA — R$ ${totalGeral.toFixed(2)} LANÇADO NO FINANCEIRO (CONVÊNIO A RECEBER).`
                : "GTO GERADA COM SUCESSO!");
            store.clear();
            setSelectedEsp('');
            setSelectedProc(null);
            setSelectedDentes([]);
            setSelectedArco(null);
            setArcoFace('');
            setArcoObs('');
        } catch (e: any) {
            toast.error((e?.message || "ERRO AO GERAR GTO.").toUpperCase());
        }
    };

    const totalGeral = store.items.reduce((sum, i) => sum + i.valorTotal, 0);

    const toggleMixed = () => {
        if (showMixed) {
            if (pacienteTipo === 'ADULTO') {
                const toRemove = selectedDentes.filter(d => parseInt(d) >= 50);
                toRemove.forEach(d => {
                    const item = store.items.find(i => i.dente === d && i.procedimentoId === selectedProc?.id);
                    if (item) store.removeItem(item.id);
                });
                setSelectedDentes(prev => prev.filter(d => parseInt(d) < 50));
            } else {
                const toRemove = selectedDentes.filter(d => parseInt(d) < 50);
                toRemove.forEach(d => {
                    const item = store.items.find(i => i.dente === d && i.procedimentoId === selectedProc?.id);
                    if (item) store.removeItem(item.id);
                });
                setSelectedDentes(prev => prev.filter(d => parseInt(d) >= 50));
            }
        }
        setShowMixed(prev => !prev);
    };

    const renderDenteBtn = (num: number | string | null, keyIdx?: number) => {
        if (num === null) return <div key={`empty-${keyIdx}`} className="w-7 h-7 sm:w-9 sm:h-9" />;
        const sStr = num.toString();
        const isDeciduo = parseInt(sStr) >= 50;
        const isSelected = selectedDentes.includes(sStr);
        const isDisabled = !!selectedProc && selectedProc.tipo_regiao !== 'DENTE';

        return (
            <button
                key={sStr}
                onClick={() => toggleDente(sStr)}
                disabled={isDisabled}
                className={`w-7 h-7 sm:w-9 sm:h-9 rounded-lg border-2 text-[9px] sm:text-[11px] font-black transition-all shadow-sm flex items-center justify-center
                    ${isSelected
                        ? isDeciduo
                            ? 'bg-amber-500 border-amber-600 text-white scale-110 z-10'
                            : 'bg-teal-600 border-teal-700 text-white scale-110 z-10'
                        : isDisabled
                            ? 'bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed opacity-50'
                            : isDeciduo
                                ? 'bg-white border-amber-200 text-amber-700 hover:border-amber-400 hover:bg-amber-50'
                                : 'bg-white border-gray-200 text-gray-700 hover:border-teal-400 hover:bg-teal-50'}
                `}
            >
                {sStr}
            </button>
        );
    };

    // ─── JSX SECTIONS ───────────────────────────────────────────────

    const step1Card = (
        <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
            <div className="flex items-center gap-3 text-teal-600 font-black text-base uppercase tracking-wider">
                <Users size={20} strokeWidth={3} /> 01. Paciente
            </div>
            {store.paciente ? (
                <div className="flex items-center justify-between bg-teal-50 border-2 border-teal-200 rounded-2xl px-4 py-3">
                    <div className="flex items-center gap-3 min-w-0">
                        <div className="w-8 h-8 bg-teal-600 rounded-full flex items-center justify-center text-white font-black text-xs flex-shrink-0">
                            {store.paciente.nome.charAt(0)}
                        </div>
                        <span className="font-black text-teal-800 text-sm uppercase truncate">{store.paciente.nome}</span>
                    </div>
                    <button onClick={() => store.setPaciente(null)}
                        className="text-xs font-bold text-teal-500 hover:text-red-500 transition-colors flex-shrink-0 ml-3 uppercase">
                        ALTERAR
                    </button>
                </div>
            ) : (
                <button onClick={() => setPatientSearchOpen(true)}
                    className="w-full p-4 bg-gray-50 border-2 border-dashed border-teal-200 rounded-2xl font-black text-teal-400 text-sm hover:bg-teal-50 hover:border-teal-400 transition-all uppercase flex items-center justify-center gap-2">
                    <Search size={16} /> SELECIONAR BENEFICIÁRIO
                </button>
            )}
        </div>
    );

    const step2Card = (
        <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-5">
            <div className="flex items-center gap-3 text-teal-500 font-black text-base uppercase tracking-wider">
                <Stethoscope size={20} strokeWidth={3} /> 02. Especialidade
            </div>
            <div className="space-y-3">
                <select
                    value={selectedEsp}
                    onChange={(e) => {
                        setSelectedEsp(e.target.value);
                        setSelectedProc(null);
                        setSelectedDentes([]);
                        setSelectedArco(null);
                        setSelectedProdutoId('');
                        setProtValor('');
                        setProtObs('');
                    }}
                    className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-700 text-sm focus:border-teal-400 outline-none transition-all uppercase"
                >
                    <option value="">ESCOLHA A ÁREA...</option>
                    {especialidades.map(es => <option key={es.id} value={es.id}>{es.nome}</option>)}
                </select>

                {selectedEsp && isProtese && (
                    <div className="space-y-3">
                        <select
                            value={selectedLab}
                            onChange={(e) => { setSelectedLab(e.target.value); setSelectedProdutoId(''); setProtValor(''); }}
                            className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-700 text-sm focus:border-teal-400 outline-none transition-all uppercase"
                        >
                            <option value="">ESCOLHA O LABORATÓRIO / PROTÉTICO...</option>
                            {laboratorios.map(l => <option key={l.id} value={l.id}>{l.nome}{l.interno ? ' (INTERNO)' : ''}</option>)}
                        </select>

                        {selectedLab && (labProdutos.length === 0 ? (
                            <div className="bg-amber-50 border-2 border-amber-100 rounded-2xl p-4 text-center">
                                <p className="text-[11px] font-black text-amber-700 uppercase tracking-wide">Este laboratório não tem produtos ativos</p>
                            </div>
                        ) : (
                            <>
                                <select
                                    value={selectedProdutoId}
                                    onChange={(e) => {
                                        setSelectedProdutoId(e.target.value);
                                        const pr = labProdutos.find(p => p.id === e.target.value);
                                        setProtValor(pr ? String(pr.preco ?? '') : '');
                                    }}
                                    className="w-full p-4 bg-white border-2 border-teal-100 rounded-2xl font-black text-gray-800 text-sm shadow-inner uppercase"
                                >
                                    <option value="">ESCOLHA A PRÓTESE...</option>
                                    {labProdutos.map(p => <option key={p.id} value={p.id}>{p.nome} — R$ {Number(p.preco || 0).toFixed(2)}</option>)}
                                </select>

                                {selectedProduto && (
                                    <>
                                        <div>
                                            <label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1.5">Valor (R$)</label>
                                            <input
                                                type="number"
                                                step="0.01"
                                                value={protValor}
                                                onChange={e => setProtValor(e.target.value)}
                                                className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-teal-400 outline-none transition-all"
                                                placeholder="0,00"
                                            />
                                        </div>
                                        <textarea
                                            value={protObs}
                                            onChange={e => setProtObs(e.target.value)}
                                            rows={2}
                                            placeholder="OBSERVAÇÃO PARA O PROTÉTICO (cor, material, dentes...)"
                                            className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl text-[11px] focus:border-amber-400 outline-none transition-all resize-none"
                                        />
                                        <div className="bg-teal-50 p-3 rounded-xl border border-teal-100">
                                            <div className="flex items-center gap-1.5 text-[10px] font-bold text-teal-800">
                                                <ChevronRight size={10} /> AO FINALIZAR A GTO, UMA OS DE PRÓTESE SERÁ ABERTA NA BANCADA DO LABORATÓRIO.
                                            </div>
                                        </div>
                                        <button
                                            onClick={handleAddProtese}
                                            className="w-full bg-[#2d6a4f] text-white py-4 rounded-2xl font-black text-sm uppercase shadow-lg shadow-green-100 hover:bg-[#1b4332] active:scale-95 transition-all flex items-center justify-center gap-2 group"
                                        >
                                            ADICIONAR PRÓTESE <ChevronRight size={16} className="group-hover:translate-x-1 transition-transform" />
                                        </button>
                                    </>
                                )}
                            </>
                        ))}
                    </div>
                )}

                {selectedEsp && !isProtese && (
                    <div className="space-y-2">
                        {filteredProcedimentos.length === 0 ? (
                            <div className="bg-amber-50 border-2 border-amber-100 rounded-2xl p-4 text-center">
                                <p className="text-[11px] font-black text-amber-700 uppercase tracking-wide">Nenhum procedimento cadastrado nesta especialidade</p>
                                <p className="text-[10px] font-bold text-amber-500 uppercase mt-1">Cadastre em Procedimentos para usá-lo aqui</p>
                            </div>
                        ) : (
                            <select
                                value={selectedProc?.id || ''}
                                onChange={(e) => {
                                    const pr = procedimentos.find(p => p.id === e.target.value);
                                    setSelectedProc(pr || null);
                                    setSelectedDentes([]);
                                    setSelectedArco(null);
                                    setArcoFace('');
                                    setArcoObs('');
                                }}
                                className="w-full p-4 bg-white border-2 border-teal-100 rounded-2xl font-black text-gray-800 text-sm shadow-inner uppercase"
                            >
                                <option value="">BUSCAR PROCEDIMENTO</option>
                                {filteredProcedimentos.map(p => <option key={p.id} value={p.id}>{p.nome}</option>)}
                            </select>
                        )}

                        {selectedProc && (
                            <div className="bg-teal-50 p-3 rounded-xl border border-teal-100">
                                <div className="flex items-center gap-1.5 text-[10px] font-bold text-teal-800">
                                    <ChevronRight size={10} />
                                    {selectedProc.tipo_regiao === 'DENTE'
                                        ? 'CLIQUE OS DENTES NO ODONTOGRAMA'
                                        : selectedProc.tipo_regiao === 'ARCO'
                                            ? 'SELECIONE O ARCO (AI/AS)'
                                            : 'PROCEDIMENTO GERAL — CLIQUE ADICIONAR'}
                                </div>
                                {selectedProc.exige_face && (
                                    <div className="flex items-center gap-1.5 text-[10px] font-bold text-red-600 mt-1">
                                        <ChevronRight size={10} /> EXIGE FACE CLÍNICA
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );

    const step3Card = (
        <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
            <div className="flex items-center gap-3 text-[#2d6a4f] font-black text-base uppercase tracking-wider">
                <Check size={20} strokeWidth={3} className="bg-green-100 p-1 rounded-full text-green-700" /> 03. Dentista Executor
            </div>
            <select
                value={store.dentista?.id || ''}
                onChange={(e) => {
                    const d = dentistas.find(d => d.id === e.target.value);
                    store.setDentista(d || null);
                }}
                className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-green-500 outline-none transition-all uppercase"
            >
                <option value="">SELECIONE O PROFISSIONAL</option>
                {dentistas.map(d => <option key={d.id} value={d.id}>{d.nome}</option>)}
            </select>

            <div className="pt-1">
                <label className="text-[11px] font-black text-gray-400 uppercase tracking-widest mb-1.5 block">Convênio / Credenciada</label>
                <select
                    value={store.credenciada || ''}
                    onChange={(e) => store.setCredenciada(e.target.value)}
                    className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-green-500 outline-none transition-all uppercase"
                >
                    <option value="">SELECIONE O CONVÊNIO</option>
                    {convenios.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)}
                </select>
            </div>
        </div>
    );

    // Step 4: only for ARCO / GERAL (face + obs + ADICIONAR button)
    const step4Card = selectedProc && selectedProc.tipo_regiao !== 'DENTE' ? (
        <div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-xl space-y-4">
            <div className="flex items-center justify-between">
                <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest">04. Face & Observações</p>
                {selectedProc.exige_face && <span className="text-red-500 text-[9px] font-black animate-pulse">* OBRIGATÓRIO</span>}
            </div>
            <div>
                <label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2">Face (O, M, D, V, L, P)</label>
                <input
                    type="text"
                    value={arcoFace}
                    onChange={e => setArcoFace(e.target.value.toUpperCase())}
                    className={`w-full p-4 border-2 rounded-2xl text-sm font-black outline-none transition-all
                        ${selectedProc.exige_face ? 'bg-red-50 border-red-100 focus:border-red-400' : 'bg-gray-50 border-gray-100 focus:border-amber-400'}`}
                    placeholder={selectedProc.exige_face ? "FACE OBRIGATÓRIA..." : "OPCIONAL"}
                />
            </div>
            <div>
                <label className="block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2 italic">Observações</label>
                <textarea
                    value={arcoObs}
                    onChange={e => setArcoObs(e.target.value)}
                    rows={3}
                    className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl text-[11px] focus:border-amber-400 outline-none transition-all resize-none"
                />
            </div>
            <button
                onClick={handleAddItem}
                className="w-full bg-[#2d6a4f] text-white py-4 rounded-2xl font-black text-sm uppercase shadow-lg shadow-green-100 hover:bg-[#1b4332] active:scale-95 transition-all flex items-center justify-center gap-2 group"
            >
                ADICIONAR ITEM <ChevronRight size={16} className="group-hover:translate-x-1 transition-transform" />
            </button>
        </div>
    ) : null;

    // Finalize button (shared)
    const finalizeBtn = (
        <div className="p-2">
            <button
                onClick={handleFinalize}
                className="w-full bg-gray-900 text-white py-5 rounded-3xl font-black text-lg uppercase shadow-xl hover:bg-black active:scale-95 transition-all flex items-center justify-center gap-3"
            >
                <Check size={22} strokeWidth={3} /> FINALIZAR GTO
            </button>
        </div>
    );

    const odontogramCard = (
        <div className="bg-white rounded-3xl border border-gray-100 shadow-xl p-3 sm:p-8 space-y-4 sm:space-y-6">
            <div className="flex justify-center mb-2 sm:mb-4">
                <div className="inline-flex bg-gray-100 p-1 rounded-xl shadow-inner">
                    <button
                        onClick={() => { setPacienteTipo('ADULTO'); setSelectedDentes([]); setShowMixed(false); }}
                        className={`px-5 sm:px-8 py-2 rounded-lg text-xs font-black transition-all uppercase ${pacienteTipo === 'ADULTO' ? 'bg-teal-600 text-white shadow-md scale-105' : 'text-gray-500 hover:text-gray-800'}`}
                    >Adulto</button>
                    <button
                        onClick={() => { setPacienteTipo('CRIANCA'); setSelectedDentes([]); setShowMixed(false); }}
                        className={`px-5 sm:px-8 py-2 rounded-lg text-xs font-black transition-all uppercase ${pacienteTipo === 'CRIANCA' ? 'bg-teal-600 text-white shadow-md scale-105' : 'text-gray-500 hover:text-gray-800'}`}
                    >Criança</button>
                </div>
            </div>

            <div className="relative border-t border-b border-gray-50 py-6 sm:py-10">
                <div className="absolute left-1/2 top-4 bottom-4 w-[2px] bg-gray-200 -translate-x-1/2"></div>
                <div className="absolute top-1/2 left-2 right-2 h-[2px] bg-gray-200 -translate-y-1/2"></div>
                <div className="grid grid-cols-2 gap-x-2 sm:gap-x-12 gap-y-6 sm:gap-y-16">
                    <div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
                        {pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q1)}
                        <div className="grid grid-cols-4 gap-1 sm:gap-2">
                            {(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q1 : DENTES_CRIANCA.q1).map((d, i) => renderDenteBtn(d, i))}
                        </div>
                    </div>
                    <div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
                        <div className="grid grid-cols-4 gap-1 sm:gap-2">
                            {(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q2 : DENTES_CRIANCA.q2).map((d, i) => renderDenteBtn(d, i))}
                        </div>
                        {pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q2)}
                    </div>
                    <div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
                        {pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q4)}
                        <div className="grid grid-cols-4 gap-1 sm:gap-2">
                            {(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q4 : DENTES_CRIANCA.q4).map((d, i) => renderDenteBtn(d, i))}
                        </div>
                    </div>
                    <div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
                        <div className="grid grid-cols-4 gap-1 sm:gap-2">
                            {(pacienteTipo === 'ADULTO' ? DENTES_ADULTO.q3 : DENTES_CRIANCA.q3).map((d, i) => renderDenteBtn(d, i))}
                        </div>
                        {pacienteTipo === 'ADULTO' && renderDenteBtn(DENTES_ADULTO.extras.q3)}
                    </div>
                </div>
            </div>

            {showMixed && (
                <div className="border-t-2 border-dashed border-amber-200 pt-4 space-y-3 animate-in fade-in slide-in-from-top-2 duration-200">
                    <p className="text-[9px] font-black text-amber-500 uppercase tracking-widest text-center">
                        {pacienteTipo === 'ADULTO' ? '— DENTES DECÍDUOS —' : '— DENTES PERMANENTES —'}
                    </p>
                    <div className="relative py-4 sm:py-6">
                        <div className="absolute left-1/2 top-2 bottom-2 w-[2px] bg-amber-100 -translate-x-1/2"></div>
                        <div className="absolute top-1/2 left-2 right-2 h-[2px] bg-amber-100 -translate-y-1/2"></div>
                        <div className="grid grid-cols-2 gap-x-2 sm:gap-x-12 gap-y-6 sm:gap-y-16">
                            <div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
                                {pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q1)}
                                <div className="grid grid-cols-4 gap-1 sm:gap-2">
                                    {(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q1 : DENTES_ADULTO.q1).map((d, i) => renderDenteBtn(d, i))}
                                </div>
                            </div>
                            <div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
                                <div className="grid grid-cols-4 gap-1 sm:gap-2">
                                    {(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q2 : DENTES_ADULTO.q2).map((d, i) => renderDenteBtn(d, i))}
                                </div>
                                {pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q2)}
                            </div>
                            <div className="flex justify-end items-center gap-1 sm:gap-2 pr-1 sm:pr-2">
                                {pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q4)}
                                <div className="grid grid-cols-4 gap-1 sm:gap-2">
                                    {(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q4 : DENTES_ADULTO.q4).map((d, i) => renderDenteBtn(d, i))}
                                </div>
                            </div>
                            <div className="flex justify-start items-center gap-1 sm:gap-2 pl-1 sm:pl-2">
                                <div className="grid grid-cols-4 gap-1 sm:gap-2">
                                    {(pacienteTipo === 'ADULTO' ? DENTES_CRIANCA.q3 : DENTES_ADULTO.q3).map((d, i) => renderDenteBtn(d, i))}
                                </div>
                                {pacienteTipo === 'CRIANCA' && renderDenteBtn(DENTES_ADULTO.extras.q3)}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            <button
                onClick={toggleMixed}
                className={`w-full py-2.5 rounded-2xl border-2 font-black text-[11px] uppercase transition-all flex items-center justify-center gap-2
                    ${showMixed ? 'border-amber-300 text-amber-600 bg-amber-50 hover:bg-amber-100' : 'border-dashed border-amber-200 text-amber-400 hover:border-amber-400 hover:bg-amber-50'}`}
            >
                {showMixed
                    ? <><X size={13} /> {pacienteTipo === 'ADULTO' ? 'REMOVER DECÍDUOS' : 'REMOVER PERMANENTES'}</>
                    : <><PlusCircle size={13} /> {pacienteTipo === 'ADULTO' ? '+ INCLUIR DENTES DECÍDUOS' : '+ INCLUIR DENTES PERMANENTES'}</>
                }
            </button>

            <div className="flex justify-center gap-4 pt-4">
                {(['AI', 'AS'] as const).map(arco => (
                    <button key={arco}
                        onClick={() => selectArco(arco)}
                        disabled={!!selectedProc && selectedProc.tipo_regiao !== 'ARCO'}
                        className={`px-10 py-3 rounded-2xl border-2 font-black text-sm uppercase transition-all shadow-sm
                            ${selectedArco === arco ? 'bg-amber-500 border-amber-600 text-white' :
                                (!!selectedProc && selectedProc.tipo_regiao !== 'ARCO')
                                    ? 'bg-gray-50 border-gray-100 text-gray-300 cursor-not-allowed opacity-50'
                                    : 'bg-white border-gray-100 text-gray-500 hover:border-amber-400'}`}
                    >
                        {arco === 'AI' ? 'AI - Inferior' : 'AS - Superior'}
                    </button>
                ))}
            </div>
        </div>
    );

    // Rascunho with inline face checkboxes + obs + dentist
    const rascunhoCard = (
        <div className="bg-white rounded-3xl border border-gray-100 overflow-hidden shadow-xl">
            <div className="bg-[#d49a4a] p-4 text-white font-black text-sm uppercase flex justify-between items-center tracking-widest">
                <span>PROCEDIMENTOS DO RASCUNHO</span>
                <div className="flex items-center gap-3">
                    <div className="bg-white/20 px-3 py-1 rounded-full text-[10px]">{store.items.length}/20</div>
                    <div className="bg-white/20 px-3 py-1 rounded-full text-[10px]">
                        R$ {totalGeral.toFixed(2)}
                    </div>
                </div>
            </div>

            <div className="p-4 sm:p-6 space-y-3">
                {store.items.length === 0 && (
                    <div className="py-14 text-center text-gray-300 font-bold uppercase flex flex-col items-center gap-4">
                        <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center outline outline-gray-100 outline-offset-4">
                            <AlertCircle size={32} />
                        </div>
                        <span className="text-xs">SELECIONE DENTES OU ARCOS<br/>PARA INICIAR O RASCUNHO</span>
                    </div>
                )}

                {store.items.map((item) => {
                    const isDeciduo = item.dente ? parseInt(item.dente) >= 50 : false;
                    return (
                        <div key={item.id}
                            className="border border-gray-100 rounded-2xl p-4 bg-gray-50/40 hover:bg-white transition-all shadow-sm">

                            {/* Header row: tooth/arco chip + procedure + value + remove */}
                            <div className="flex items-start justify-between gap-2 mb-3">
                                <div className="flex items-center gap-2.5 min-w-0 flex-1">
                                    <span className={`w-10 h-10 rounded-xl flex items-center justify-center text-[11px] font-black flex-shrink-0 border-2
                                        ${item.dente
                                            ? isDeciduo
                                                ? 'bg-amber-100 text-amber-700 border-amber-200'
                                                : 'bg-teal-100 text-teal-700 border-teal-200'
                                            : 'bg-amber-100 text-amber-600 border-amber-200'}`}>
                                        {item.dente || item.arco || '--'}
                                    </span>
                                    <div className="min-w-0 flex-1">
                                        <div className="font-black text-xs text-gray-900 uppercase leading-tight truncate">
                                            {item.descricao}
                                        </div>
                                        <div className="flex items-center gap-1 mt-0.5 text-[9px] text-gray-400 font-bold uppercase">
                                            <Stethoscope size={8} />
                                            <span className="truncate">{store.dentista?.nome || 'SEM DENTISTA'}</span>
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-1.5 flex-shrink-0">
                                    <span className="text-[10px] font-black text-green-600 whitespace-nowrap">
                                        R$ {item.valorTotal.toFixed(2)}
                                    </span>
                                    <button
                                        onClick={() => {
                                            store.removeItem(item.id);
                                            if (item.dente) setSelectedDentes(prev => prev.filter(d => d !== item.dente));
                                        }}
                                        className="text-gray-300 hover:text-red-500 transition-colors p-0.5"
                                    >
                                        <Trash2 size={15} />
                                    </button>
                                </div>
                            </div>

                            {/* Face checkboxes — only for tooth items */}
                            {item.dente && (
                                <div className="flex items-center gap-1.5 mb-2.5 flex-wrap">
                                    <span className="text-[9px] font-black text-gray-400 uppercase tracking-wider w-full mb-1">
                                        FACE CLÍNICA:
                                        {!item.face && (
                                            <span className="text-gray-300 font-normal normal-case ml-1 italic">não selecionada</span>
                                        )}
                                    </span>
                                    {FACES.map(f => (
                                        <button
                                            key={f}
                                            onClick={() => store.updateItem(item.id, { face: item.face === f ? '' : f })}
                                            className={`w-9 h-9 rounded-xl border-2 text-[11px] font-black transition-all flex items-center justify-center
                                                ${item.face === f
                                                    ? 'bg-teal-600 border-teal-700 text-white shadow-md'
                                                    : 'bg-white border-gray-200 text-gray-400 hover:border-teal-300 hover:text-teal-500 hover:bg-teal-50'}`}
                                        >
                                            {f}
                                        </button>
                                    ))}
                                </div>
                            )}

                            {/* Observação */}
                            <textarea
                                value={item.observacao || ''}
                                onChange={e => store.updateItem(item.id, { observacao: e.target.value })}
                                placeholder="OBSERVAÇÃO CLÍNICA..."
                                rows={2}
                                className="w-full px-3 py-2.5 bg-white border border-gray-100 rounded-xl text-[11px] resize-none outline-none focus:border-amber-300 transition-colors placeholder:text-gray-300 leading-relaxed"
                            />
                        </div>
                    );
                })}

                {store.items.length > 0 && (
                    <div className="pt-4 border-t-2 border-dotted border-gray-200 flex justify-between items-center">
                        <button className="flex items-center gap-2 text-teal-600 font-black text-[11px] uppercase hover:bg-teal-50 px-4 py-2 rounded-xl transition-all">
                            <Camera size={16} /> ANEXAR DOCUMENTOS
                        </button>
                        <div className="text-right">
                            <p className="text-[10px] font-black text-gray-400 uppercase tracking-[0.2em] mb-1">TOTAL</p>
                            <h3 className="text-2xl font-black text-gray-900 px-4 py-2 bg-gray-50 rounded-2xl border border-gray-100 shadow-inner">
                                R$ {totalGeral.toFixed(2)}
                            </h3>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );

    // ─── RENDER ─────────────────────────────────────────────────────

    return (
        <div className="space-y-6 pb-20 lg:pb-0">
            <PageHeader
                title="LANÇAR GTO"
                description="MONTAGEM DINÂMICA DE GUIA ODONTOLÓGICA (GTO)."
            />

            {/* ─── DESKTOP LAYOUT ─────────────────────────────── */}
            <div className="hidden lg:grid grid-cols-12 gap-6 items-start">
                <div className="col-span-8 space-y-6">
                    {odontogramCard}
                    {rascunhoCard}
                </div>
                <div className="col-span-4 space-y-4 sticky top-6">
                    {step1Card}
                    {step2Card}
                    {step3Card}
                    {step4Card}
                    {finalizeBtn}
                </div>
            </div>

            {/* ─── MOBILE LAYOUT (3 páginas) ──────────────────── */}
            <div className="lg:hidden">
                {mobilePage === 1 && (
                    <div className="space-y-4">
                        {step1Card}
                        {step2Card}
                        {step3Card}
                    </div>
                )}
                {mobilePage === 2 && odontogramCard}
                {mobilePage === 3 && (
                    <div className="space-y-4">
                        {step4Card}
                        {rascunhoCard}
                    </div>
                )}
            </div>

            {/* ─── MOBILE FOOTER NAV ──────────────────────────── */}
            <div className="fixed bottom-0 left-0 right-0 z-40 lg:hidden bg-white/95 backdrop-blur-sm border-t border-gray-200 shadow-xl px-4 py-3 flex items-center justify-between gap-2">
                {mobilePage > 1 ? (
                    <button
                        onClick={() => setMobilePage(p => (p - 1) as 1 | 2 | 3)}
                        className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl border-2 border-gray-200 font-black text-xs text-gray-500 hover:bg-gray-50 transition-all uppercase"
                    >
                        <ChevronLeft size={14} /> VOLTAR
                    </button>
                ) : (
                    <div className="w-24" />
                )}

                <div className="flex items-center gap-2">
                    {([1, 2, 3] as const).map(p => (
                        <button key={p} onClick={() => setMobilePage(p)}
                            className={`transition-all rounded-full ${mobilePage === p ? 'w-6 h-2.5 bg-teal-600' : 'w-2.5 h-2.5 bg-gray-200 hover:bg-gray-400'}`}
                        />
                    ))}
                </div>

                {mobilePage < 3 ? (
                    <button
                        onClick={() => setMobilePage(p => (p + 1) as 1 | 2 | 3)}
                        className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl bg-teal-600 text-white font-black text-xs hover:bg-teal-700 active:scale-95 transition-all uppercase shadow-md"
                    >
                        PRÓXIMO <ChevronRight size={14} />
                    </button>
                ) : (
                    <button
                        onClick={handleFinalize}
                        className="flex items-center gap-1.5 px-4 py-2.5 rounded-2xl bg-gray-900 text-white font-black text-xs hover:bg-black active:scale-95 transition-all uppercase shadow-md"
                    >
                        FINALIZAR <Check size={14} />
                    </button>
                )}
            </div>

            {/* ─── PATIENT SEARCH MODAL ───────────────────────── */}
            {patientSearchOpen && (
                <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center backdrop-blur-sm p-4">
                    <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                        <div className="px-6 py-5 border-b border-gray-100 flex justify-between items-center">
                            <h3 className="font-black text-gray-900 uppercase tracking-wide text-sm flex items-center gap-2">
                                <Search size={16} className="text-teal-600" /> BUSCAR PACIENTE
                            </h3>
                            <button
                                onClick={() => { setPatientSearchOpen(false); setPatientSearchTerm(''); }}
                                className="text-gray-400 hover:text-gray-600 p-1 hover:bg-gray-100 rounded-full transition-colors"
                            >
                                <X size={20} />
                            </button>
                        </div>
                        <div className="p-5 space-y-3">
                            <input
                                autoFocus
                                type="text"
                                value={patientSearchTerm}
                                onChange={e => setPatientSearchTerm(e.target.value.toUpperCase())}
                                placeholder="NOME OU CPF..."
                                className="w-full p-4 bg-gray-50 border-2 border-gray-100 rounded-2xl font-black text-gray-800 text-sm focus:border-teal-500 outline-none transition-all uppercase"
                            />
                            <div className="max-h-72 overflow-y-auto space-y-1">
                                {patientResults.length === 0 ? (
                                    <div className="py-10 text-center text-gray-300 font-bold uppercase text-xs">
                                        {searchingPatients ? 'BUSCANDO...' : (patientSearchTerm ? 'NENHUM PACIENTE ENCONTRADO' : 'CARREGANDO...')}
                                    </div>
                                ) : (
                                    patientResults.map(p => (
                                        <button
                                            key={p.id}
                                            onClick={() => {
                                                store.setPaciente(p);
                                                setPatientSearchOpen(false);
                                                setPatientSearchTerm('');
                                            }}
                                            className="w-full text-left px-4 py-3 hover:bg-teal-50 rounded-xl transition-all flex items-center gap-3 group"
                                        >
                                            <div className="w-9 h-9 bg-teal-100 rounded-full flex items-center justify-center text-teal-600 font-black text-sm flex-shrink-0 group-hover:bg-teal-600 group-hover:text-white transition-colors">
                                                {p.nome.charAt(0)}
                                            </div>
                                            <div className="min-w-0">
                                                <div className="font-black text-sm text-gray-800 uppercase truncate">{p.nome}</div>
                                                {p.cpf && <div className="text-[10px] text-gray-400 font-bold">{p.cpf}</div>}
                                            </div>
                                        </button>
                                    ))
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};
