import React, { useState, useEffect } from 'react';
import { Plus, Edit, Trash2, X, FileText, Stethoscope, Award, BookOpen, RefreshCw, Database, Loader2, Mail, Phone, ClipboardList, GripVertical, Share2, Check, Clock, ArrowRight, Activity } from 'lucide-react';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { HybridBackend } from '../services/backend.ts';
import { Dentista, Especialidade, Plano, Procedimento, ProcedimentoValorPlano, DentistaHorario } from '../types.ts';
import { useHybridBackend } from '../hooks/useHybridBackend.ts';
import { useToast } from '../contexts/ToastContext.tsx';
import { PageHeader } from '../components/PageHeader.tsx';
import { GoogleConnectButton } from '../components/GoogleConnectButton.tsx';

const AdminSection: React.FC<{ title: string; buttonLabel: string; onButtonClick: () => void; children: React.ReactNode }> =
    ({ title, buttonLabel, onButtonClick, children }) => (
        <div className="space-y-6">
            <PageHeader title={title}>
                <button
                    onClick={onButtonClick}
                    className="bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-blue-700 font-bold text-xs uppercase transition-colors shadow-sm"
                >
                    <Plus size={18} /> {buttonLabel}
                </button>
            </PageHeader>
            {children}
        </div>
    );

const DentistHoursModal: React.FC<{ dentist: Dentista; clinicaId: string; onClose: () => void }> = ({ dentist, clinicaId, onClose }) => {
    const { data: horarios, refresh } = useHybridBackend<DentistaHorario[]>(() => HybridBackend.getHorariosByDentista(dentist.id, clinicaId));
    const toast = useToast();
    const dias = ['DOMINGO', 'SEGUNDA', 'TERÇA', 'QUARTA', 'QUINTA', 'SEXTA', 'SÁBADO'];

    const handleAdd = async (e: React.FormEvent) => {
        e.preventDefault();
        const fd = new FormData(e.target as HTMLFormElement);
        await HybridBackend.saveHorario({
            dentista_id: dentist.id,
            clinica_id: clinicaId,
            dia_semana: parseInt(fd.get('dia') as string),
            hora_inicio: fd.get('inicio') as string,
            hora_fim: fd.get('fim') as string,
            ativo: true
        });
        toast.success("HORÁRIO ADICIONADO!");
        refresh();
    };

    return (
        <div className="fixed inset-0 bg-black/60 z-[60] 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 zoom-in-95 duration-200">
                <div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                    <div>
                        <h3 className="text-lg font-black text-gray-900 uppercase leading-tight">ESCALA DE ATENDIMENTO</h3>
                        <p className="text-[10px] text-blue-600 font-bold uppercase">{dentist.nome}</p>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-xl transition-colors"><X size={20} /></button>
                </div>
                <div className="p-6 space-y-6">
                    <form onSubmit={handleAdd} className="grid grid-cols-1 md:grid-cols-4 gap-3 bg-blue-50/50 p-4 rounded-xl border border-blue-100">
                        <select name="dia" className="bg-white border-blue-200 border rounded-lg p-2 text-xs font-bold uppercase" required>
                            {dias.map((d, i) => <option key={i} value={i}>{d}</option>)}
                        </select>
                        <input name="inicio" type="time" className="bg-white border-blue-200 border rounded-lg p-2 text-xs font-bold" required />
                        <input name="fim" type="time" className="bg-white border-blue-200 border rounded-lg p-2 text-xs font-bold" required />
                        <button type="submit" className="bg-blue-600 text-white rounded-lg font-black text-[10px] uppercase hover:bg-blue-700 transition-all flex items-center justify-center gap-2">
                            <Plus size={14} /> ADICIONAR
                        </button>
                    </form>

                    <div className="space-y-2 flex-1 overflow-y-auto pr-2">
                        {horarios?.map(h => (
                            <div key={h.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-xl border border-gray-100 hover:border-blue-200 transition-all group">
                                <div className="flex items-center gap-4">
                                    <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center shadow-sm text-blue-600 border border-gray-100 font-black text-[10px]">
                                        {dias[h.dia_semana].substring(0, 3)}
                                    </div>
                                    <div className="flex items-center gap-2 text-xs font-black text-gray-700">
                                        <Clock size={14} className="text-gray-400" />
                                        <span>{h.hora_inicio.substring(0, 5)}</span>
                                        <ArrowRight size={12} className="text-gray-300" />
                                        <span>{h.hora_fim.substring(0, 5)}</span>
                                    </div>
                                </div>
                                <button
                                    onClick={async () => { await HybridBackend.deleteHorario(h.id); refresh(); toast.success("REMOVIDO!"); }}
                                    className="p-2 text-gray-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all opacity-0 group-hover:opacity-100"
                                >
                                    <Trash2 size={16} />
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

// --- DENTISTAS ---
export const DentistasView: React.FC = () => {
    const activeWorkspace = HybridBackend.getActiveWorkspace();
    const { data: dentistas, isLoading, error, refresh } = useHybridBackend<Dentista[]>(() => HybridBackend.getDentistas(activeWorkspace?.id));
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingDentista, setEditingDentista] = useState<Partial<Dentista> | null>(null);
    const [isHoursModalOpen, setIsHoursModalOpen] = useState(false);
    const [selectedDentist, setSelectedDentist] = useState<Dentista | null>(null);
    const [connectedAccounts, setConnectedAccounts] = useState<any[]>([]);
    const toast = useToast();

    const fetchGoogleStatus = async () => {
        try {
            const response = await fetch('/api/auth/google/status');
            const data = await response.json();
            setConnectedAccounts(data);
        } catch (error) {
            console.error("Erro ao buscar status do Google:", error);
        }
    };

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

    useEffect(() => {
        if (!isModalOpen) return;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') setIsModalOpen(false);
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isModalOpen]);

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        const data = Object.fromEntries(formData);

        try {
            if (editingDentista && editingDentista.id) {
                await HybridBackend.updateDentista({ ...editingDentista, ...data } as Dentista);
                toast.success("DENTISTA ATUALIZADO!");
            } else {
                await HybridBackend.saveDentista({ ...data, ativo: true } as any);
                toast.success("DENTISTA CADASTRADO!");
            }
            setIsModalOpen(false);
            refresh();
        } catch {
            toast.error("ERRO AO SALVAR DENTISTA.");
        }
    };

    const handleDelete = async (id: string) => {
        if (window.confirm("TEM CERTEZA QUE DESEJA EXCLUIR ESTE DENTISTA?")) {
            await HybridBackend.deleteDentista(id);
            toast.success("Dentista excluído.");
            refresh();
        }
    }

    const [copiedId, setCopiedId] = useState<string | null>(null);

    const handleInviteDentist = async (d: Dentista) => {
        try {
            const activeW = HybridBackend.getActiveWorkspace();
            const res = await fetch('/api/dentistas/magic-link', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ clinicaId: activeW.id, dentistName: d.nome })
            });
            const { link } = await res.json();
            await navigator.clipboard.writeText(link);
            setCopiedId(d.id);
            toast.success("LINK MÁGICO COPIADO!");
            setTimeout(() => setCopiedId(null), 2000);
        } catch {
            toast.error("ERRO AO GERAR LINK.");
        }
    };

    return (
        <AdminSection title="DENTISTAS & ESPECIALISTAS" buttonLabel="NOVO DENTISTA" onButtonClick={() => { setEditingDentista({}); setIsModalOpen(true); }}>
            {isLoading && <Loader2 className="animate-spin text-blue-500" />}
            {error && <p className="text-red-500">Erro: {error.message}</p>}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {dentistas?.map(d => (
                    <div key={d.id} className="bg-white border border-gray-200 rounded-xl shadow-sm hover:shadow-md transition-shadow flex flex-col">
                        <div className="p-5 flex-grow">
                            <div className="flex items-start justify-between">
                                <div>
                                    <h3 className="font-bold text-gray-900 uppercase">{d.nome}</h3>
                                    <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded-full uppercase">{d.especialidade}</span>
                                </div>
                                <div className="w-4 h-4 rounded-full border-2 border-white shadow" style={{ backgroundColor: d.corAgenda }}></div>
                            </div>
                            <div className="mt-4 space-y-2 text-xs text-gray-500">
                                <p className="flex items-center gap-2 font-medium"><Mail size={14} /> {d.email}</p>
                                <p className="flex items-center gap-2 font-medium"><Phone size={14} /> {d.telefone}</p>
                            </div>

                            <div className="mt-5 border-t border-gray-50 pt-4 flex items-center gap-2">
                                <div className="flex-1">
                                    <GoogleConnectButton
                                        ownerId={d.id}
                                        isConnected={connectedAccounts.some(a => a.owner_id === d.id)}
                                        onStatusChange={fetchGoogleStatus}
                                    />
                                </div>
                                <button
                                    onClick={() => handleInviteDentist(d)}
                                    title="COMPARTILHAR LINK DE CADASTRO"
                                    className={`p-2.5 rounded-xl border transition-all ${copiedId === d.id ? 'bg-green-50 text-green-600 border-green-200' : 'bg-gray-50 text-gray-400 border-gray-100 hover:bg-blue-50 hover:text-blue-600 hover:border-blue-100'}`}
                                >
                                    {copiedId === d.id ? <Check size={18} /> : <Share2 size={18} />}
                                </button>
                            </div>
                        </div>
                        <div className="border-t border-gray-100 p-2 grid grid-cols-3 gap-1">
                            <button onClick={() => { setEditingDentista(d); setIsModalOpen(true); }} className="text-[10px] uppercase font-bold text-gray-600 hover:bg-gray-100 py-2 rounded-md flex items-center justify-center gap-1"><Edit size={12} /> EDITAR</button>
                            <button onClick={() => { setSelectedDentist(d); setIsHoursModalOpen(true); }} className="text-[10px] uppercase font-bold text-blue-600 hover:bg-blue-50 py-2 rounded-md flex items-center justify-center gap-1"><Clock size={12} /> ESCALA</button>
                            <button onClick={() => handleDelete(d.id)} className="text-[10px] uppercase font-bold text-red-500 hover:bg-red-50 py-2 rounded-md flex items-center justify-center gap-1"><Trash2 size={12} /> EXCLUIR</button>
                        </div>
                    </div>
                ))}
            </div>

            {isModalOpen && (
                <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-xl flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                        <div className="px-5 py-4 border-b border-gray-200 flex justify-between items-center flex-shrink-0 bg-gradient-to-r from-blue-50 to-white">
                            <h3 className="text-lg font-bold text-gray-800 uppercase">{editingDentista?.id ? 'EDITAR' : 'NOVO'} DENTISTA</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-1.5 transition-colors"><X size={22} /></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-5 lg:p-8">
                            <form onSubmit={handleSave} className="space-y-4 max-w-2xl mx-auto">
                                <input id="dentista-nome" type="text" name="nome" placeholder="NOME COMPLETO" defaultValue={editingDentista?.nome} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" required />
                                <input id="dentista-email" type="email" name="email" placeholder="EMAIL" defaultValue={editingDentista?.email} className="w-full border border-gray-300 rounded-lg p-2" required />
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <input id="dentista-telefone" type="text" name="telefone" placeholder="TELEFONE" defaultValue={editingDentista?.telefone} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" />
                                    <input id="dentista-celular" type="text" name="celular" placeholder="WHATSAPP / CELULAR" defaultValue={editingDentista?.celular} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <input id="dentista-cro" type="text" name="cro" placeholder="NÚMERO CRO" defaultValue={editingDentista?.cro} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" />
                                    <select id="dentista-cro-uf" name="cro_uf" defaultValue={editingDentista?.cro_uf || 'MS'} className="w-full border border-gray-300 rounded-lg p-2">
                                        <option value="MS">MS</option><option value="SP">SP</option><option value="RJ">RJ</option><option value="MG">MG</option><option value="PR">PR</option><option value="SC">SC</option>
                                    </select>
                                </div>
                                <input id="dentista-especialidade" type="text" name="especialidade" placeholder="ESPECIALIDADE PRINCIPAL" defaultValue={editingDentista?.especialidade} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" required />
                                <div>
                                    <label htmlFor="dentista-cor" className="text-xs font-bold text-gray-500 uppercase">COR NA AGENDA</label>
                                    <input id="dentista-cor" type="color" name="corAgenda" defaultValue={editingDentista?.corAgenda || '#3B82F6'} className="w-full h-10 border border-gray-300 rounded-lg p-1" />
                                </div>
                                <button type="submit" className="w-full bg-green-600 text-white py-2 rounded-lg font-bold hover:bg-green-700 uppercase">SALVAR</button>
                            </form>
                        </div>
                    </div>
                </div>
            )}

            {isHoursModalOpen && selectedDentist && activeWorkspace && (
                <DentistHoursModal
                    dentist={selectedDentist}
                    clinicaId={activeWorkspace.id}
                    onClose={() => { setIsHoursModalOpen(false); setSelectedDentist(null); }}
                />
            )}
        </AdminSection>
    );
};

// --- ESPECIALIDADES ---
export const EspecialidadesView: React.FC = () => {
    const { data: especialidades, isLoading, error, refresh } = useHybridBackend<Especialidade[]>(HybridBackend.getEspecialidades);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingEsp, setEditingEsp] = useState<Partial<Especialidade> | null>(null);
    const toast = useToast();

    useEffect(() => {
        if (!isModalOpen) return;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') setIsModalOpen(false);
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isModalOpen]);

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        const data = Object.fromEntries(formData);

        try {
            if (editingEsp && editingEsp.id) {
                await HybridBackend.updateEspecialidade({ ...editingEsp, ...data } as Especialidade);
                toast.success("ESPECIALIDADE ATUALIZADA!");
            } else {
                await HybridBackend.saveEspecialidade(data as any);
                toast.success("ESPECIALIDADE SALVA!");
            }
            setIsModalOpen(false);
            refresh();
        } catch {
            toast.error("ERRO AO SALVAR ESPECIALIDADE.");
        }
    };

    const handleDelete = async (id: string) => {
        if (window.confirm("TEM CERTEZA QUE DESEJA EXCLUIR ESTA ESPECIALIDADE?")) {
            await HybridBackend.deleteEspecialidade(id);
            toast.success("Especialidade excluída.");
            refresh();
        }
    }

    const onDragEnd = async (result: any) => {
        if (!result.destination || !especialidades) return;

        const items = Array.from(especialidades);
        const [reorderedItem] = items.splice(result.source.index, 1);
        items.splice(result.destination.index, 0, reorderedItem);

        const updatedOrders = items.map((item, index) => ({
            id: item.id,
            ordem: index
        }));

        try {
            await HybridBackend.reorderEspecialidades(updatedOrders);
            toast.success("ORDEM ATUALIZADA!");
            refresh();
        } catch {
            toast.error("ERRO AO REORDENAR.");
        }
    };

    return (
        <AdminSection title="ESPECIALIDADES CLÍNICAS" buttonLabel="NOVA ESPECIALIDADE" onButtonClick={() => { setEditingEsp({}); setIsModalOpen(true); }}>
            <div className="bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden">
                <table className="w-full text-sm">
                    <thead className="bg-gray-50 text-gray-500 uppercase text-xs font-bold">
                        <tr>
                            <th className="px-6 py-3 text-left w-10"></th>
                            <th className="px-6 py-3 text-left">NOME</th>
                            <th className="px-6 py-3 text-left">DESCRIÇÃO</th>
                            <th className="px-6 py-3 text-right">AÇÕES</th>
                        </tr>
                    </thead>
                    <DragDropContext onDragEnd={onDragEnd}>
                        <Droppable droppableId="especialidades">
                            {(provided) => (
                                <tbody {...provided.droppableProps} ref={provided.innerRef} className="divide-y divide-gray-100">
                                    {isLoading && <tr><td colSpan={4} className="p-6 text-center"><Loader2 className="animate-spin text-blue-500 mx-auto" /></td></tr>}
                                    {error && <tr><td colSpan={4} className="p-6 text-center text-red-500">{error.message}</td></tr>}
                                    {especialidades?.map((esp, index) => (
                                        <Draggable key={esp.id} draggableId={esp.id} index={index}>
                                            {(provided, snapshot) => (
                                                <tr
                                                    ref={provided.innerRef}
                                                    {...provided.draggableProps}
                                                    className={`${snapshot.isDragging ? 'bg-blue-50 shadow-md ring-1 ring-blue-200' : 'bg-white'} transition-shadow`}
                                                >
                                                    <td className="px-6 py-4 text-gray-400 cursor-grab active:cursor-grabbing" {...provided.dragHandleProps}>
                                                        <GripVertical size={18} />
                                                    </td>
                                                    <td className="px-6 py-4 font-bold text-gray-800">{esp.nome}</td>
                                                    <td className="px-6 py-4 text-gray-600">{esp.descricao}</td>
                                                    <td className="px-6 py-4 text-right">
                                                        <div className="flex justify-end gap-2">
                                                            <button onClick={() => { setEditingEsp(esp); setIsModalOpen(true); }} className="p-2 text-gray-500 hover:bg-gray-100 rounded-md"><Edit size={16} /></button>
                                                            <button onClick={() => handleDelete(esp.id)} className="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 rounded-md"><Trash2 size={16} /></button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            )}
                                        </Draggable>
                                    ))}
                                    {provided.placeholder}
                                </tbody>
                            )}
                        </Droppable>
                    </DragDropContext>
                </table>
            </div>

            {isModalOpen && (
                <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-xl flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                        <div className="px-5 py-4 border-b border-gray-200 flex justify-between items-center flex-shrink-0 bg-gradient-to-r from-blue-50 to-white">
                            <h3 className="text-lg font-bold text-gray-800 uppercase">{editingEsp?.id ? 'EDITAR' : 'NOVA'} ESPECIALIDADE</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-1.5 transition-colors"><X size={22} /></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-5 lg:p-8">
                            <form onSubmit={handleSave} className="space-y-4 max-w-2xl mx-auto">
                                <input id="esp-nome" name="nome" placeholder="NOME DA ESPECIALIDADE" defaultValue={editingEsp?.nome} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" required />
                                <textarea id="esp-desc" name="descricao" placeholder="BREVE DESCRIÇÃO" defaultValue={editingEsp?.descricao} className="w-full border border-gray-300 rounded-lg p-2 h-24 uppercase-textarea"></textarea>
                                <button type="submit" className="w-full bg-green-600 text-white py-2 rounded-lg font-bold hover:bg-green-700 uppercase">SALVAR</button>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </AdminSection>
    );
};

// --- PROCEDIMENTOS ---
export const ProcedimentosView: React.FC = () => {
    const { data: procedimentos, isLoading, error, refresh } = useHybridBackend<Procedimento[]>(HybridBackend.getProcedimentos);
    const { data: especialidades } = useHybridBackend<Especialidade[]>(HybridBackend.getEspecialidades);
    const { data: planos } = useHybridBackend<Plano[]>(HybridBackend.getPlanos);

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingProcedimento, setEditingProcedimento] = useState<Partial<Procedimento> | null>(null);
    const [planValues, setPlanValues] = useState<Partial<ProcedimentoValorPlano>[]>([]);
    const toast = useToast();

    useEffect(() => {
        if (!isModalOpen) return;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') setIsModalOpen(false);
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isModalOpen]);


    useEffect(() => {
        if (editingProcedimento) {
            setPlanValues(editingProcedimento.valoresPlanos || []);
            // Set initial category if new
            if (!editingProcedimento.id && !editingProcedimento.categoria) {
                setEditingProcedimento(prev => ({ ...prev, categoria: 'Particular' }));
            }
        }
    }, [editingProcedimento]);

    const suggestInternalCode = () => {
        const nextId = (procedimentos?.length || 0) + 1;
        setEditingProcedimento(prev => ({ ...prev, codigoInterno: nextId.toString() }));
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        const data: any = Object.fromEntries(formData.entries());

        const esp = especialidades?.find(es => es.id === data.especialidadeId);

        const payload: Partial<Procedimento> = {
            id: editingProcedimento?.id,
            nome: data.nome,
            codigo: data.codigo,
            codigoInterno: data.codigoInterno,
            categoria: data.categoria,
            descricao: data.descricao,
            especialidadeId: data.especialidadeId,
            especialidadeNome: esp?.nome || '',
            valorParticular: parseFloat(data.valorParticular),
            tipo_regiao: editingProcedimento?.tipo_regiao || 'GERAL',
            exige_face: editingProcedimento?.tipo_regiao === 'DENTE' ? !!editingProcedimento?.exige_face : false,
            valoresPlanos: planValues.map(pv => ({
                planoId: pv.planoId!,
                planoNome: planos?.find(p => p.id === pv.planoId)?.nome || '',
                valor: parseFloat(pv.valor as any),
                codigoPlano: pv.codigoPlano || ''
            })),
        };

        try {
            if (payload.id) {
                await HybridBackend.updateProcedimento(payload as Procedimento);
                toast.success("PROCEDIMENTO ATUALIZADO!");
            } else {
                await HybridBackend.saveProcedimento(payload);
                toast.success("PROCEDIMENTO SALVO!");
            }
            setIsModalOpen(false);
            refresh();
        } catch {
            toast.error("ERRO AO SALVAR PROCEDIMENTO.");
        }
    };

    const handleDelete = async (id: string) => {
        if (window.confirm("TEM CERTEZA QUE DESEJA EXCLUIR ESTE PROCEDIMENTO?")) {
            await HybridBackend.deleteProcedimento(id);
            toast.success("Procedimento excluído.");
            refresh();
        }
    };

    const handleAddPlanValue = () => setPlanValues(prev => [...prev, { planoId: '', valor: 0, codigoPlano: '' }]);
    const handleRemovePlanValue = (index: number) => setPlanValues(prev => prev.filter((_, i) => i !== index));
    const handlePlanValueChange = (index: number, field: 'planoId' | 'valor' | 'codigoPlano', value: string) => {
        const newValues = [...planValues];
        newValues[index] = { ...newValues[index], [field]: value };
        setPlanValues(newValues);
    };

    const onDragEnd = async (result: any) => {
        if (!result.destination || !procedimentos) return;

        const items = Array.from(procedimentos);
        const [reorderedItem] = items.splice(result.source.index, 1);
        items.splice(result.destination.index, 0, reorderedItem);

        const updatedOrders = items.map((item, index) => ({
            id: item.id,
            ordem: index
        }));

        try {
            await HybridBackend.reorderProcedimentos(updatedOrders);
            toast.success("ORDEM DOS PROCEDIMENTOS ATUALIZADA!");
            refresh();
        } catch {
            toast.error("ERRO AO REORDENAR PROCEDIMENTOS.");
        }
    };

    return (
        <AdminSection title="PROCEDIMENTOS E VALORES" buttonLabel="NOVO PROCEDIMENTO" onButtonClick={() => { setEditingProcedimento({}); setIsModalOpen(true); }}>
            <div className="bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden">
                <table className="w-full text-sm">
                    <thead className="bg-gray-50 text-gray-500 uppercase text-xs font-bold">
                        <tr>
                            <th className="px-6 py-3 text-left w-10"></th>
                            <th className="px-6 py-3 text-left">NOME</th>
                            <th className="px-6 py-3 text-left">CÓDIGO (TUSS/INT)</th>
                            <th className="px-6 py-3 text-left">CATEGORIA</th>
                            <th className="px-6 py-3 text-left">ESPECIALIDADE</th>
                            <th className="px-6 py-3 text-left">VALOR PARTICULAR</th>
                            <th className="px-6 py-3 text-right">AÇÕES</th>
                        </tr>
                    </thead>
                    <DragDropContext onDragEnd={onDragEnd}>
                        <Droppable droppableId="procedimentos">
                            {(provided) => (
                                <tbody {...provided.droppableProps} ref={provided.innerRef} className="divide-y divide-gray-100">
                                    {isLoading && <tr><td colSpan={7} className="p-6 text-center"><Loader2 className="animate-spin text-blue-500 mx-auto" /></td></tr>}
                                    {error && <tr><td colSpan={7} className="p-6 text-center text-red-500">{error.message}</td></tr>}
                                    {procedimentos?.map((proc, index) => (
                                        <Draggable key={proc.id} draggableId={proc.id} index={index}>
                                            {(provided, snapshot) => (
                                                <tr
                                                    ref={provided.innerRef}
                                                    {...provided.draggableProps}
                                                    className={`${snapshot.isDragging ? 'bg-blue-50 shadow-md ring-1 ring-blue-200' : 'bg-white'} transition-shadow`}
                                                >
                                                    <td className="px-6 py-4 text-gray-400 cursor-grab active:cursor-grabbing" {...provided.dragHandleProps}>
                                                        <GripVertical size={18} />
                                                    </td>
                                                    <td className="px-6 py-4 font-bold text-gray-800">{proc.nome}</td>
                                                    <td className="px-6 py-4">
                                                        <div className="flex flex-col gap-1">
                                                            <span className="text-[10px] font-bold text-gray-400 uppercase">TUSS: {proc.codigo || '---'}</span>
                                                            <span className="text-[10px] font-bold text-blue-600 uppercase bg-blue-50 px-1.5 py-0.5 rounded w-fit">INT: {proc.codigoInterno || '---'}</span>
                                                        </div>
                                                    </td>
                                                    <td className="px-6 py-4"><span className="text-xs font-bold px-2 py-1 rounded-full bg-gray-100 text-gray-600 uppercase">{proc.categoria}</span></td>
                                                    <td className="px-6 py-4 text-gray-600">{proc.especialidadeNome}</td>
                                                    <td className="px-6 py-4 font-semibold text-gray-700">R$ {Number(proc.valorParticular).toFixed(2)}</td>
                                                    <td className="px-6 py-4 text-right">
                                                        <div className="flex justify-end gap-2">
                                                            <button onClick={() => { setEditingProcedimento(proc); setIsModalOpen(true); }} className="p-2 text-gray-500 hover:bg-gray-100 rounded-md"><Edit size={16} /></button>
                                                            <button onClick={() => handleDelete(proc.id)} className="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 rounded-md"><Trash2 size={16} /></button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            )}
                                        </Draggable>
                                    ))}
                                    {provided.placeholder}
                                </tbody>
                            )}
                        </Droppable>
                    </DragDropContext>
                </table>
            </div>

            {isModalOpen && (
                <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-xl flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                        <div className="px-5 py-4 border-b border-gray-200 flex justify-between items-center flex-shrink-0 bg-gradient-to-r from-blue-50 to-white">
                            <h3 className="text-lg font-bold text-gray-800 uppercase">{editingProcedimento?.id ? 'EDITAR' : 'NOVO'} PROCEDIMENTO</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-1.5 transition-colors"><X size={22} /></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-5 lg:p-8">
                            <form onSubmit={handleSave} className="space-y-4 max-w-2xl mx-auto pb-4">
                                <input name="nome" placeholder="NOME DO PROCEDIMENTO" defaultValue={editingProcedimento?.nome} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" required />
                                <div className="grid grid-cols-3 gap-4">
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase">CATEGORIA</label>
                                        <select
                                            name="categoria"
                                            value={editingProcedimento?.categoria || 'Particular'}
                                            onChange={(e) => {
                                                const cat = e.target.value as any;
                                                setEditingProcedimento(prev => ({ ...prev, categoria: cat }));
                                                if (cat === 'Particular' && !editingProcedimento?.codigoInterno) {
                                                    suggestInternalCode();
                                                }
                                            }}
                                            className="w-full border border-gray-300 rounded-lg p-2 bg-white uppercase-select"
                                            required
                                        >
                                            <option value="Particular">Particular</option>
                                            <option value="Plano">Plano</option>
                                            <option value="Convênio">Convênio</option>
                                            <option value="Outros">Outros</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase">CÓDIGO TUSS</label>
                                        <input
                                            name="codigo"
                                            placeholder={editingProcedimento?.categoria === 'Plano' ? "00000000" : "OPCIONAL"}
                                            defaultValue={editingProcedimento?.codigo}
                                            className={`w-full border border-gray-300 rounded-lg p-2 uppercase-input ${editingProcedimento?.categoria !== 'Plano' ? 'bg-gray-50' : ''}`}
                                            required={editingProcedimento?.categoria === 'Plano'}
                                        />
                                    </div>
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase flex justify-between">
                                            CÓDIGO INTERNO
                                            {editingProcedimento?.categoria !== 'Particular' && (
                                                <button type="button" onClick={suggestInternalCode} className="text-blue-600 hover:text-blue-800">
                                                    <RefreshCw size={12} />
                                                </button>
                                            )}
                                        </label>
                                        <input
                                            name="codigoInterno"
                                            placeholder={editingProcedimento?.categoria === 'Particular' ? "AUTO (CONTAGEM + 1)" : "EX: 101"}
                                            value={editingProcedimento?.codigoInterno || ''}
                                            onChange={(e) => setEditingProcedimento(prev => ({ ...prev, codigoInterno: e.target.value }))}
                                            className={`w-full border border-gray-300 rounded-lg p-2 uppercase-input ${editingProcedimento?.categoria === 'Particular' ? 'bg-gray-50 text-blue-600 font-bold' : ''}`}
                                            required={editingProcedimento?.categoria !== 'Particular'}
                                        />
                                    </div>
                                </div>
                                <textarea name="descricao" placeholder="BREVE DESCRIÇÃO" defaultValue={editingProcedimento?.descricao} className="w-full border border-gray-300 rounded-lg p-2 h-20 uppercase-textarea"></textarea>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase">ESPECIALIDADE</label>
                                        <select name="especialidadeId" defaultValue={editingProcedimento?.especialidadeId} className="w-full border border-gray-300 rounded-lg p-2 bg-white uppercase-select" required>
                                            <option value="">SELECIONE UMA ESPECIALIDADE</option>
                                            {especialidades?.map(e => <option key={e.id} value={e.id}>{e.nome}</option>)}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="text-xs font-bold text-gray-500 uppercase">VALOR PARTICULAR (R$)</label>
                                        <input type="number" step="0.01" name="valorParticular" placeholder="0.00" defaultValue={editingProcedimento?.valorParticular} className="w-full border border-gray-300 rounded-lg p-2" required />
                                    </div>
                                </div>

                                <div className="bg-blue-50/50 p-4 rounded-xl border border-blue-100 space-y-4">
                                    <h4 className="text-[10px] font-black text-blue-600 uppercase tracking-widest flex items-center gap-2">
                                        <Activity size={12} /> REGRA DO ODONTOGRAMA (GTO)
                                    </h4>

                                    <div className="space-y-3">
                                        <label className="text-xs font-bold text-gray-700 uppercase">EXIGÊNCIA DE REGIÃO NO LANÇAMENTO</label>
                                        <div className="grid grid-cols-3 gap-2">
                                            {[
                                                { id: 'GERAL', label: 'PROCED. GERAL', desc: 'SEM ODONTOGRAMA' },
                                                { id: 'DENTE', label: 'DENTE ESPECÍFICO', desc: 'LIBERA NÚMEROS' },
                                                { id: 'ARCO', label: 'ARCO COMPLETO', desc: 'LIBERA AI / AS' }
                                            ].map((opt) => (
                                                <label
                                                    key={opt.id}
                                                    className={`
                                                        relative flex flex-col p-3 rounded-lg border-2 cursor-pointer transition-all
                                                        ${(editingProcedimento?.tipo_regiao || 'GERAL') === opt.id
                                                            ? 'border-blue-600 bg-blue-50 ring-2 ring-blue-100'
                                                            : 'border-gray-200 bg-white hover:border-gray-300'}
                                                    `}
                                                >
                                                    <input
                                                        type="radio"
                                                        name="tipo_regiao"
                                                        value={opt.id}
                                                        checked={(editingProcedimento?.tipo_regiao || 'GERAL') === opt.id}
                                                        onChange={(e) => setEditingProcedimento(prev => ({ ...prev, tipo_regiao: e.target.value as any }))}
                                                        className="sr-only"
                                                    />
                                                    <span className="text-[10px] font-black uppercase text-gray-900 leading-tight">{opt.label}</span>
                                                    <span className="text-[9px] font-bold text-gray-400 mt-1 uppercase">{opt.desc}</span>
                                                </label>
                                            ))}
                                        </div>
                                    </div>

                                    {(editingProcedimento?.tipo_regiao === 'DENTE') && (
                                        <div className="pt-2 animate-in slide-in-from-top-2 duration-200">
                                            <label className="flex items-center gap-3 p-3 bg-white rounded-lg border border-blue-200 cursor-pointer hover:bg-blue-50/50 transition-colors">
                                                <div className="relative flex items-center">
                                                    <input
                                                        type="checkbox"
                                                        name="exige_face"
                                                        checked={!!editingProcedimento?.exige_face}
                                                        onChange={(e) => setEditingProcedimento(prev => ({ ...prev, exige_face: e.target.checked }))}
                                                        className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                                    />
                                                </div>
                                                <div className="flex flex-col">
                                                    <span className="text-[11px] font-black text-gray-800 uppercase">Exigir preenchimento de Face?</span>
                                                    <span className="text-[9px] font-bold text-gray-400 uppercase">(O, M, D, V, L, P) será obrigatório na GTO</span>
                                                </div>
                                            </label>
                                        </div>
                                    )}
                                </div>

                                <div className="pt-4">
                                    <h4 className="font-bold text-gray-700 uppercase mb-2">VALORES PARA PLANOS / CONVÊNIOS</h4>
                                    <div className="space-y-2">
                                        {planValues.map((pv, index) => (
                                            <div key={index} className="flex flex-col md:flex-row items-center gap-2 bg-gray-50 p-2 rounded-lg border">
                                                <select value={pv.planoId} onChange={(e) => handlePlanValueChange(index, 'planoId', e.target.value)} className="flex-1 border border-gray-300 rounded-lg p-2 bg-white uppercase-select">
                                                    <option value="">SELECIONE UM PLANO</option>
                                                    {planos?.filter(p => p.tipo !== 'Particular').map(p => <option key={p.id} value={p.id}>{p.nome}</option>)}
                                                </select>
                                                <input type="number" step="0.01" placeholder="VALOR (R$)" value={pv.valor} onChange={(e) => handlePlanValueChange(index, 'valor', e.target.value)} className="w-32 border border-gray-300 rounded-lg p-2" />
                                                <input type="text" placeholder="CÓD. PLANO" value={pv.codigoPlano} onChange={(e) => handlePlanValueChange(index, 'codigoPlano', e.target.value)} className="w-32 border border-gray-300 rounded-lg p-2 uppercase-input" />
                                                <button type="button" onClick={() => handleRemovePlanValue(index)} className="p-2 text-red-500 hover:bg-red-100 rounded-md"><Trash2 size={16} /></button>
                                            </div>
                                        ))}
                                    </div>
                                    <button type="button" onClick={handleAddPlanValue} className="mt-2 text-xs font-bold text-blue-600 hover:underline uppercase flex items-center gap-1"><Plus size={14} /> ADICIONAR VALOR DE PLANO</button>
                                </div>

                                <div className="pt-4 flex-shrink-0">
                                    <button type="submit" className="w-full bg-green-600 text-white py-4 rounded-xl font-black hover:bg-green-700 uppercase text-xs shadow-lg shadow-green-100 transition-all active:scale-[0.98]">
                                        SALVAR PROCEDIMENTO
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </AdminSection>
    );
};


// --- PLANOS ---
export const PlanosView: React.FC = () => {
    const { data: planos, isLoading, error, refresh } = useHybridBackend<Plano[]>(HybridBackend.getPlanos);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingPlano, setEditingPlano] = useState<Partial<Plano> | null>(null);
    const toast = useToast();

    useEffect(() => {
        if (!isModalOpen) return;
        const handleKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') setIsModalOpen(false);
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isModalOpen]);

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        const formData = new FormData(e.target as HTMLFormElement);
        const data = Object.fromEntries(formData);

        try {
            if (editingPlano && editingPlano.id) {
                await HybridBackend.updatePlano({ ...editingPlano, ...data } as Plano);
                toast.success("PLANO ATUALIZADO!");
            } else {
                await HybridBackend.savePlano(data as any);
                toast.success("PLANO SALVO!");
            }
            setIsModalOpen(false);
            refresh();
        } catch {
            toast.error("ERRO AO SALVAR PLANO.");
        }
    };

    const handleDelete = async (id: string) => {
        if (window.confirm("TEM CERTEZA QUE DESEJA EXCLUIR ESTE PLANO?")) {
            await HybridBackend.deletePlano(id);
            toast.success("Plano excluído.");
            refresh();
        }
    }

    return (
        <AdminSection title="PLANOS E CONVÊNIOS" buttonLabel="NOVO PLANO" onButtonClick={() => { setEditingPlano({}); setIsModalOpen(true); }}>
            {isLoading && <Loader2 className="animate-spin text-blue-500" />}
            {error && <p className="text-red-500">Erro: {error.message}</p>}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {planos?.map(p => (
                    <div key={p.id} className="bg-white border border-gray-200 rounded-xl shadow-sm hover:shadow-md transition-shadow flex flex-col overflow-hidden" style={{ borderTop: `4px solid ${p.corCartao}` }}>
                        <div className="p-5 flex-grow">
                            <div className="flex justify-between items-start">
                                <h3 className="font-bold text-gray-900 uppercase">{p.nome}</h3>
                                <span className="text-xs font-bold text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full uppercase">{p.tipo}</span>
                            </div>
                            <p className="text-sm text-gray-600 mt-2">DESCONTO PADRÃO: <span className="font-bold">{p.descontoPadrao}%</span></p>
                        </div>
                        <div className="border-t border-gray-100 p-2 flex gap-2 bg-gray-50/50">
                            <button onClick={() => { setEditingPlano(p); setIsModalOpen(true); }} className="flex-1 text-xs uppercase font-bold text-gray-600 hover:bg-gray-100 py-2 rounded-md flex items-center justify-center gap-2"><Edit size={14} /> EDITAR</button>
                            <button onClick={() => handleDelete(p.id)} className="flex-1 text-xs uppercase font-bold text-red-500 hover:bg-red-50 py-2 rounded-md flex items-center justify-center gap-2"><Trash2 size={14} /> EXCLUIR</button>
                        </div>
                    </div>
                ))}
            </div>

            {isModalOpen && (
                <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-xl flex flex-col overflow-hidden animate-in fade-in zoom-in-50 duration-200">
                        <div className="px-5 py-4 border-b border-gray-200 flex justify-between items-center flex-shrink-0 bg-gradient-to-r from-blue-50 to-white">
                            <h3 className="text-lg font-bold text-gray-800 uppercase">{editingPlano?.id ? 'EDITAR' : 'NOVO'} PLANO</h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg p-1.5 transition-colors"><X size={22} /></button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-5 lg:p-8">
                            <form onSubmit={handleSave} className="space-y-4 max-w-2xl mx-auto">
                                <input name="nome" placeholder="NOME DO PLANO/CONVÊNIO" defaultValue={editingPlano?.nome} className="w-full border border-gray-300 rounded-lg p-2 uppercase-input" required />
                                <select name="tipo" defaultValue={editingPlano?.tipo || 'Convenio'} className="w-full border border-gray-300 rounded-lg p-2 bg-white uppercase-select" required>
                                    <option>Convenio</option>
                                    <option>Particular</option>
                                    <option>Parceria</option>
                                </select>
                                <input type="number" name="descontoPadrao" placeholder="DESCONTO PADRÃO (%)" defaultValue={editingPlano?.descontoPadrao} className="w-full border border-gray-300 rounded-lg p-2" />
                                <div>
                                    <label className="text-xs font-bold text-gray-500 uppercase">COR DO CARTÃO</label>
                                    <input type="color" name="corCartao" defaultValue={editingPlano?.corCartao || '#1f2937'} className="w-full h-10 border border-gray-300 rounded-lg p-1" />
                                </div>
                                <button type="submit" className="w-full bg-green-600 text-white py-2 rounded-lg font-bold hover:bg-green-700 uppercase">SALVAR</button>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </AdminSection>
    );
};


// --- SYNC ---
const SYNC_TABS = ['pacientes', 'agendamentos', 'financeiro', 'leads', 'guias'];

export const SyncView: React.FC = () => {
    const [logs, setLogs] = useState<string[]>([]);
    const [operation, setOperation] = useState<'push' | 'pull' | 'import-legacy' | null>(null);
    const [status, setStatus] = useState<any>(null);
    const toast = useToast();

    const authHeaders = {
        'Authorization': `Bearer ${localStorage.getItem('SCOREODONTO_AUTH_TOKEN')}`,
        'Content-Type': 'application/json'
    };

    const loadStatus = async () => {
        try {
            const res = await fetch('/api/sync/status', { headers: authHeaders });
            if (res.ok) setStatus(await res.json());
        } catch {}
    };

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

    const runSync = async (dir: 'push' | 'pull' | 'import-legacy') => {
        setOperation(dir);
        const labels: Record<string, string> = {
            push: 'BACKUP PostgreSQL → Google Sheets',
            pull: 'RESTAURAR Google Sheets → PostgreSQL',
            'import-legacy': 'IMPORTAR PACIENTES (aba PACIENTES-CONSULTT-CLINIC)...'
        };
        setLogs([`>>> ${labels[dir]}...`]);
        try {
            const res = await fetch(`/api/sync/${dir}`, { method: 'POST', headers: authHeaders });
            const data = await res.json();
            setLogs(data.logs || []);
            if (data.success) {
                const msgs: Record<string, string> = {
                    push: 'BACKUP REALIZADO!',
                    pull: 'DADOS RESTAURADOS!',
                    'import-legacy': `${data.imported ?? 0} PACIENTES IMPORTADOS!`
                };
                toast.success(msgs[dir]);
                loadStatus();
            } else {
                toast.error('ERRO NA SINCRONIZAÇÃO. VERIFIQUE OS LOGS.');
            }
        } catch (e: any) {
            setLogs(prev => [...prev, `[ERRO] ${e.message}`]);
            toast.error('FALHA NA CONEXÃO.');
        } finally {
            setOperation(null);
        }
    };

    const fmtDate = (iso: string | undefined) => iso
        ? new Date(iso).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
        : '—';

    return (
        <div className="max-w-5xl mx-auto space-y-6">
            <PageHeader
                title="BACKUP & SINCRONIZAÇÃO"
                description="POSTGRESQL ↔ GOOGLE SHEETS"
            >
                <div className="flex gap-3">
                    <button
                        onClick={() => runSync('push')}
                        disabled={!!operation}
                        className={`px-4 py-2 rounded-xl flex items-center gap-2 text-xs font-black uppercase transition-all shadow-sm ${operation ? 'bg-gray-200 text-gray-400 cursor-not-allowed' : 'bg-green-600 hover:bg-green-700 text-white shadow-green-100'}`}
                    >
                        <RefreshCw size={15} className={operation === 'push' ? 'animate-spin' : ''} />
                        {operation === 'push' ? 'ENVIANDO...' : 'BACKUP AGORA'}
                    </button>
                    <button
                        onClick={() => runSync('pull')}
                        disabled={!!operation}
                        className={`px-4 py-2 rounded-xl flex items-center gap-2 text-xs font-black uppercase transition-all shadow-sm ${operation ? 'bg-gray-200 text-gray-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700 text-white shadow-blue-100'}`}
                    >
                        <Database size={15} className={operation === 'pull' ? 'animate-spin' : ''} />
                        {operation === 'pull' ? 'IMPORTANDO...' : 'RESTAURAR DO BACKUP'}
                    </button>
                    <button
                        onClick={() => runSync('import-legacy')}
                        disabled={!!operation}
                        title="Importa pacientes da aba PACIENTES-CONSULTT-CLINIC (Apps Script)"
                        className={`px-4 py-2 rounded-xl flex items-center gap-2 text-xs font-black uppercase transition-all shadow-sm ${operation ? 'bg-gray-200 text-gray-400 cursor-not-allowed' : 'bg-amber-500 hover:bg-amber-600 text-white shadow-amber-100'}`}
                    >
                        <Database size={15} className={operation === 'import-legacy' ? 'animate-spin' : ''} />
                        {operation === 'import-legacy' ? 'IMPORTANDO...' : 'IMPORTAR PLANILHA LEGADA'}
                    </button>
                </div>
            </PageHeader>

            {/* Status por tabela */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                <div className="px-6 py-4 border-b border-gray-50">
                    <h3 className="text-xs font-black text-gray-500 uppercase tracking-widest">ESTADO DAS TABELAS</h3>
                </div>
                <div className="divide-y divide-gray-50">
                    {SYNC_TABS.map(tab => {
                        const s = status?.syncStatus?.[tab];
                        const count = status?.counts?.[tab];
                        return (
                            <div key={tab} className="flex items-center justify-between px-6 py-4">
                                <div className="flex items-center gap-3">
                                    <div className={`w-2 h-2 rounded-full ${s?.lastPush ? 'bg-green-400' : 'bg-gray-200'}`} />
                                    <span className="text-sm font-black uppercase text-gray-700">{tab}</span>
                                </div>
                                <div className="flex items-center gap-8 text-right">
                                    <div>
                                        <p className="text-[9px] font-bold text-gray-400 uppercase">No banco</p>
                                        <p className="text-sm font-black text-gray-800">{count ?? '—'}</p>
                                    </div>
                                    <div>
                                        <p className="text-[9px] font-bold text-gray-400 uppercase">Último backup</p>
                                        <p className="text-xs font-bold text-gray-600">{fmtDate(s?.lastPush)}</p>
                                    </div>
                                    <div>
                                        <p className="text-[9px] font-bold text-gray-400 uppercase">Registros no backup</p>
                                        <p className="text-xs font-bold text-gray-600">{s?.count ?? '—'}</p>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
                {status?.spreadsheetId && (
                    <div className="px-6 py-3 bg-gray-50 border-t border-gray-100 flex items-center gap-2">
                        <span className="text-[10px] font-bold text-gray-400 uppercase">PLANILHA:</span>
                        <span className="text-[10px] font-mono text-blue-600 truncate">{status.spreadsheetId}</span>
                    </div>
                )}
            </div>

            {/* Terminal */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                <div className="px-6 py-4 border-b border-gray-50 flex items-center justify-between">
                    <h3 className="text-xs font-black text-gray-500 uppercase tracking-widest">LOG DE OPERAÇÃO</h3>
                    {logs.length > 0 && (
                        <button onClick={() => setLogs([])} className="text-[10px] font-bold text-gray-400 hover:text-gray-600 uppercase">LIMPAR</button>
                    )}
                </div>
                <div className="p-4">
                    <div className="bg-gray-950 rounded-xl p-4 font-mono text-xs text-green-400 min-h-[160px] max-h-80 overflow-y-auto">
                        {logs.length === 0
                            ? <span className="text-gray-600">AGUARDANDO OPERAÇÃO...</span>
                            : logs.map((log, i) => (
                                <div key={i} className={`mb-1 pl-2 border-l-2 ${log.startsWith('[ERRO]') ? 'border-red-500 text-red-400' : log.startsWith('[✓]') ? 'border-green-400 text-green-300' : 'border-gray-700'}`}>
                                    {log}
                                </div>
                            ))
                        }
                        {operation && <div className="animate-pulse text-green-500 mt-1">▋</div>}
                    </div>
                </div>

                <div className="bg-amber-50 border-t border-amber-100 px-6 py-3 flex items-start gap-3">
                    <Database size={14} className="text-amber-600 mt-0.5 flex-shrink-0" />
                    <p className="text-[10px] text-amber-700 font-bold uppercase leading-relaxed">
                        BACKUP AUTOMÁTICO: cada alteração de paciente, agendamento, financeiro ou lead é enviada
                        para a planilha automaticamente (com delay de 5s para agrupar alterações). Use "Restaurar" para
                        recuperar dados da planilha caso o banco seja reiniciado.
                    </p>
                </div>
            </div>
        </div>
    );
};