import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import API_KEY from '../components/utils/apiKeys.js';
import AgendamentoCadastroManager from '../pages/AgendamentoCadastroManager.jsx';
// Removidos imports não utilizados no novo fluxo
import { GetAllDoctors } from '../components/utils/Functions-Endpoints/Doctor.js';
import { useAuth } from '../components/utils/AuthProvider.js';
import dayjs from 'dayjs';
import 'dayjs/locale/pt-br';
import isBetween from 'dayjs/plugin/isBetween';
import localeData from 'dayjs/plugin/localeData';
import { Search, ChevronLeft, ChevronRight, Edit, Trash2, CheckCircle } from 'lucide-react';
import "../pages/style/Agendamento.css";
import '../pages/style/FilaEspera.css';
import Spinner from '../components/Spinner.jsx';


dayjs.locale('pt-br');
dayjs.extend(isBetween);
dayjs.extend(localeData);


const Agendamento = () => {
    const navigate = useNavigate();
    const { getAuthorizationHeader, user } = useAuth();
    const authHeader = getAuthorizationHeader();

    // ID do médico que você quer visualizar
    const ID_MEDICO_ESPECIFICO = "078d2a67-b4c1-43c8-ae32-c1e75bb5b3df";

    const [listaTodosAgendamentos, setListaTodosAgendamentos] = useState([]);
    const [selectedID, setSelectedId] = useState('0');
    const [filaEsperaData, setFilaEsperaData] = useState([]);
    const [FiladeEspera, setFiladeEspera] = useState(false);
    const [PageNovaConsulta, setPageConsulta] = useState(false);
    const [DictAgendamentosOrganizados, setAgendamentosOrganizados] = useState({});
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [ListaDeMedicos, setListaDeMedicos] = useState([]);
    const [FiltredTodosMedicos, setFiltredTodosMedicos] = useState([]);
    const [searchTermDoctor, setSearchTermDoctor] = useState('');
    const [MedicoFiltrado, setMedicoFiltrado] = useState({ id: "vazio" });
    const [motivoCancelamento, setMotivoCancelamento] = useState("");
    const [showSpinner, setShowSpinner] = useState(true);
    const [waitlistSearch, setWaitlistSearch] = useState('');
    const [waitSortKey, setWaitSortKey] = useState(null);
    const [waitSortDir, setWaitSortDir] = useState('asc');
    const [waitPage, setWaitPage] = useState(1);
    const [waitPerPage, setWaitPerPage] = useState(10);
    const [cacheMedicos, setCacheMedicos] = useState({});
    const [cachePacientes, setCachePacientes] = useState({});
    const [currentDate, setCurrentDate] = useState(dayjs());
    const [selectedDay, setSelectedDay] = useState(dayjs());
    const [agendamentoParaEdicao, setAgendamentoParaEdicao] = useState(null);
    const [quickJump, setQuickJump] = useState({
        month: currentDate.month(),
        year: currentDate.year()
    });

    // ✨ ALTERAÇÃO PRINCIPAL: A busca agora filtra pelo ID do médico direto na API
    const fetchAppointments = useCallback(async () => {
        if (!authHeader) return;
        setShowSpinner(true);
        const myHeaders = new Headers();
        myHeaders.append("Authorization", authHeader);
        myHeaders.append("apikey", API_KEY);
        const requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' };

        // A URL agora contém o filtro para o ID do médico específico
        const apiUrl = `https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?doctor_id=eq.${ID_MEDICO_ESPECIFICO}&select=*`;

        try {
            const res = await fetch(apiUrl, requestOptions);
            const data = await res.json();
            setListaTodosAgendamentos(data || []);
        } catch (err) {
            console.error('Erro ao buscar agendamentos', err);
            setListaTodosAgendamentos([]);
        } finally {
            setShowSpinner(false);
        }
    }, [authHeader, ID_MEDICO_ESPECIFICO]);


    const updateAppointmentStatus = useCallback(async (id, updates) => {
        setShowSpinner(true);
        const myHeaders = new Headers();
        myHeaders.append("Authorization", authHeader);
        myHeaders.append("apikey", API_KEY);
        myHeaders.append("Content-Type", "application/json");
        myHeaders.append("Prefer", "return=representation");
        const requestOptions = { method: 'PATCH', headers: myHeaders, body: JSON.stringify(updates) };
        try {
            const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${id}`, requestOptions);
            if (response.ok) {
                await fetchAppointments();
                return true;
            } else {
                console.error('Erro ao atualizar agendamento:', await response.text());
                return false;
            }
        } catch (error) {
            console.error('Erro de rede/servidor:', error);
            return false;
        } finally {
            setShowSpinner(false);
        }
    }, [authHeader, fetchAppointments]);


    const deleteConsulta = useCallback(async (id) => {
        const success = await updateAppointmentStatus(id, { status: "cancelled", cancellation_reason: motivoCancelamento, updated_at: new Date().toISOString() });
        if (success) {
            setShowDeleteModal(false);
            setMotivoCancelamento("");
            setSelectedId('0');
        } else {
            alert("Falha ao cancelar a consulta.");
        }
    }, [motivoCancelamento, updateAppointmentStatus]);


    const confirmConsulta = useCallback(async (id) => {
        const success = await updateAppointmentStatus(id, { status: "agendado", cancellation_reason: null, updated_at: new Date().toISOString() });
        if (success) {
            setSelectedId('0');
        } else {
            alert("Falha ao reverter o cancelamento.");
        }
    }, [updateAppointmentStatus]);

    useEffect(() => {
        if(authHeader) {
            fetchAppointments();
            // A busca de todos os médicos pode continuar caso a secretária precise ver a lista
            if (user?.role !== 'doctor') {
                GetAllDoctors(authHeader).then(docs => {
                    if (docs) {
                        setListaDeMedicos(docs.map(d => ({ nomeMedico: d.full_name, idMedico: d.id })));
                    }
                });
            }
        }
    }, [authHeader, fetchAppointments, user?.role]);

    useEffect(() => {
        const processData = async () => {
            // Como os dados já vêm filtrados da API, não precisamos mais da verificação de 'user' aqui
            if (!listaTodosAgendamentos.length) {
                setAgendamentosOrganizados({});
                setFilaEsperaData([]);
                return;
            }

            setShowSpinner(true);

            // ✨ SIMPLIFICAÇÃO: Não é mais necessário filtrar por `user.role`,
            // pois a API já retornou apenas os agendamentos do médico desejado.
            const appointmentsToShow = listaTodosAgendamentos;

            const patientIdsToFetch = new Set();
            const doctorIdsToFetch = new Set();

            appointmentsToShow.forEach(ag => {
                if (ag.patient_id && !cachePacientes[ag.patient_id]) {
                    patientIdsToFetch.add(ag.patient_id);
                }
                if (ag.doctor_id && !cacheMedicos[ag.doctor_id]) {
                    doctorIdsToFetch.add(ag.doctor_id);
                }
            });

            const fetchPromises = [];

            if (patientIdsToFetch.size > 0) {
                const query = `id=in.(${Array.from(patientIdsToFetch).join(',')})`;
                fetchPromises.push(
                    fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients?${query}&select=*`, {
                        headers: { apikey: API_KEY, Authorization: authHeader }
                    }).then(res => res.json())
                );
            } else {
                fetchPromises.push(Promise.resolve(null)); // Mantém a ordem do Promise.all
            }

            if (doctorIdsToFetch.size > 0) {
                const query = `id=in.(${Array.from(doctorIdsToFetch).join(',')})`;
                fetchPromises.push(
                    fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctors?${query}&select=id,full_name`, {
                         headers: { apikey: API_KEY, Authorization: authHeader }
                    }).then(res => res.json())
                );
            } else {
                fetchPromises.push(Promise.resolve(null));
            }
            
            const [newPatients, newDoctors] = await Promise.all(fetchPromises);

            const updatedPatientCache = { ...cachePacientes };
            if (newPatients) newPatients.forEach(p => updatedPatientCache[p.id] = p);

            const updatedDoctorCache = { ...cacheMedicos };
            if (newDoctors) newDoctors.forEach(d => updatedDoctorCache[d.id] = d);
            
            setCachePacientes(updatedPatientCache);
            setCacheMedicos(updatedDoctorCache);

            const newDict = {};
            const newFila = [];

            for (const agendamento of appointmentsToShow) {
                const medico = updatedDoctorCache[agendamento.doctor_id];
                const paciente = updatedPatientCache[agendamento.patient_id];

                if (!medico || !paciente) continue;

                const agendamentoMelhorado = {
                    ...agendamento,
                    medico_nome: medico.full_name || 'N/A',
                    paciente_nome: paciente.full_name || 'N/A',
                    paciente_cpf: paciente.cpf || 'N/A'
                };

                if (agendamento.status === "requested") {
                    newFila.push({ agendamento: agendamentoMelhorado, Infos: agendamentoMelhorado });
                } else {
                    const DiaAgendamento = dayjs(agendamento.scheduled_at).format("YYYY-MM-DD");
                    if (!newDict[DiaAgendamento]) newDict[DiaAgendamento] = [];
                    newDict[DiaAgendamento].push(agendamentoMelhorado);
                }
            }

            for (const key in newDict) {
                newDict[key].sort((a, b) => new Date(a.scheduled_at) - new Date(b.scheduled_at));
            }

            setAgendamentosOrganizados(newDict);
            setFilaEsperaData(newFila);
            setShowSpinner(false);
        };

        processData();
    }, [listaTodosAgendamentos, authHeader]); // Removido 'user' das dependências pois não é mais usado aqui

    // O restante do código permanece o mesmo...

    const handleEditConsulta = (agendamento) => {
        setAgendamentoParaEdicao(agendamento);
        setPageConsulta(true);
    };

    const handleSearchMedicos = (term) => {
        setSearchTermDoctor(term);
        if (term.trim()) {
            const filtered = ListaDeMedicos.filter(medico =>
                medico.nomeMedico.toLowerCase().includes(term.toLowerCase())
            );
            setFiltredTodosMedicos(filtered);
        } else {
            setFiltredTodosMedicos([]);
            setMedicoFiltrado({ id: "vazio" });
        }
    };
    
    const generateDateGrid = () => {
        const grid = [];
        const startOfMonth = currentDate.startOf('month');
        let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day');
        for (let i = 0; i < 42; i++) {
            grid.push(currentDay);
            currentDay = currentDay.add(1, 'day');
        }
        return grid;
    };

    const dateGrid = useMemo(() => generateDateGrid(), [currentDate]);
    const weekDays = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'];
    const handleDateClick = (day) => setSelectedDay(day);
const DeleteModal = () => (
    <div className="modal fade show" style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }} tabIndex="-1">
        <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content">
                <div className="modal-header" style={{ backgroundColor: '#f8d7da', color: '#721c24' }}>
                    <h5 className="modal-title">Confirmação de Cancelamento</h5>
                    <button type="button" className="btn-close" onClick={() => setShowDeleteModal(false)}></button>
                </div>
                <div className="modal-body">
                    <p>Qual o motivo do cancelamento? (Opcional)</p>
                    <textarea className="form-control" rows="3" value={motivoCancelamento} onChange={(e) => setMotivoCancelamento(e.target.value)}></textarea>
                </div>
                <div className="modal-footer justify-content-center">
                    <button type="button" className="btn btn-secondary" onClick={() => { setShowDeleteModal(false); setMotivoCancelamento(""); }}>Manter Agendamento</button>
                    {/* ✨ Botão sempre ativo ✨ */}
                    <button type="button" className="btn btn-danger" onClick={() => deleteConsulta(selectedID)}>
                        <Trash2 size={16} className="me-1" /> Confirmar Cancelamento
                    </button>
                </div>
            </div>
        </div>
    </div>
);


    useEffect(() => {
        setQuickJump({
            month: currentDate.month(),
            year: currentDate.year()
        });
    }, [currentDate]);
    
    const filaEsperaFiltrada = useMemo(() => {
        if (!waitlistSearch.trim()) return filaEsperaData;
        const term = waitlistSearch.toLowerCase();
        return filaEsperaData.filter(item =>
            (item?.Infos?.paciente_nome?.toLowerCase() || '').includes(term) ||
            (item?.Infos?.paciente_cpf?.toLowerCase() || '').includes(term) ||
            (item?.Infos?.medico_nome?.toLowerCase() || '').includes(term)
        );
    }, [waitlistSearch, filaEsperaData]);

    const applySortingWaitlist = useCallback((arr) => {
        if (!Array.isArray(arr) || !waitSortKey) return arr;
        const copy = [...arr];
        const key = waitSortKey;
        const dir = waitSortDir === 'asc' ? 1 : -1;
        copy.sort((a, b) => {
            const valA = key === 'data' ? new Date(a.agendamento.scheduled_at) : (a.Infos?.[`${key}_nome`] || '');
            const valB = key === 'data' ? new Date(b.agendamento.scheduled_at) : (b.Infos?.[`${key}_nome`] || '');
            if (valA < valB) return -1 * dir;
            if (valA > valB) return 1 * dir;
            return 0;
        });
        return copy;
    }, [waitSortKey, waitSortDir]);

    const filaEsperaOrdenada = useMemo(() => applySortingWaitlist(filaEsperaFiltrada), [filaEsperaFiltrada, applySortingWaitlist]);
    const waitTotalPages = Math.ceil(filaEsperaOrdenada.length / waitPerPage) || 1;
    const waitIndiceInicial = (waitPage - 1) * waitPerPage;
    const waitIndiceFinal = waitIndiceInicial + waitPerPage;
    const filaEsperaPaginada = filaEsperaOrdenada.slice(waitIndiceInicial, waitIndiceFinal);

    const gerarNumerosWaitPages = () => {
        const paginas = [];
        const paginasParaMostrar = 5;
        let inicio = Math.max(1, waitPage - Math.floor(paginasParaMostrar / 2));
        let fim = Math.min(waitTotalPages, inicio + paginasParaMostrar - 1);
        inicio = Math.max(1, fim - paginasParaMostrar + 1);
        for (let i = inicio; i <= fim; i++) paginas.push(i);
        return paginas;
    };

    useEffect(() => { setWaitPage(1); }, [waitlistSearch, waitSortKey, waitSortDir]);

    const handleQuickJumpChange = (type, value) => {
        setQuickJump(prev => ({ ...prev, [type]: Number(value) }));
    };

    const applyQuickJump = () => {
        let newDate = dayjs().year(quickJump.year).month(quickJump.month).date(1);
        setCurrentDate(newDate);
        setSelectedDay(newDate);
    };

    return (
        <div>
            <h1>Agendar nova consulta</h1>
            <div className="btns-gerenciamento-e-consulta" style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
                <button 
                    className="btn btn-primary" 
                    onClick={() => {
                        setAgendamentoParaEdicao(null); 
                        setPageConsulta(true);
                    }}
                >
                    <i className="bi bi-plus-circle"></i> Adicionar Consulta
                </button>
                <button className="manage-button btn" onClick={() => navigate("/secretaria/excecoes-disponibilidade")}><i className="bi bi-gear-fill me-1"></i> Gerenciar Exceções</button>
                <button className='manage-button btn' onClick={() => navigate('/secretaria/disponibilidade')}><i className="bi bi-gear-fill me-1"></i> Mudar Disponibilidade</button>
            </div>
            {!PageNovaConsulta ? (
                <div className='atendimento-eprocura'>
                    {user?.role !== 'doctor' && (
                        <div className='unidade-selecionarprofissional'>
                            <div className='busca-atendimento-container'>
                                <div className='input-e-dropdown-wrapper'>
                                    <div className='busca-atendimento'>
                                        <div className='mb-5'>
                                            <input type="text" placeholder="Filtrar atendimento do medico..." value={searchTermDoctor} onChange={(e) => handleSearchMedicos(e.target.value)} />
                                        </div>
                                    </div>
                                    {searchTermDoctor && FiltredTodosMedicos.length > 0 && (
                                        <div className='dropdown-medicos'>
                                            {FiltredTodosMedicos.map((medico) => (
                                                <div
                                                    key={medico.idMedico}
                                                    className='dropdown-item'
                                                    onClick={() => {
                                                        setSearchTermDoctor(medico.nomeMedico);
                                                        setFiltredTodosMedicos([]);
                                                        setMedicoFiltrado({ id: medico.idMedico });
                                                    }}
                                                >
                                                    <p>{medico.nomeMedico}</p>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                    <div className='container-btns-agenda-fila_esepera'>
                        <button className={`btn-agenda ${!FiladeEspera ? "opc-agenda-ativo" : ""}`} onClick={() => { setFiladeEspera(false); }}>Agenda</button>
                        <button className={`btn-fila-espera ${FiladeEspera ? "opc-filaespera-ativo" : ""}`} onClick={() => { setFiladeEspera(true); }}>Fila de espera</button>
                    </div>
                    <section className='calendario-ou-filaespera'>
                        {!FiladeEspera ? (
                            <div className="calendar-wrapper">
                                <div className="calendar-info-panel">
                                    <div className="info-date-display"><span>{selectedDay.format('MMM')}</span><strong>{selectedDay.format('DD')}</strong></div>
                                    <div className="info-details"><h3>{selectedDay.format('dddd')}</h3><p>{selectedDay.format('D [de] MMMM [de] YYYY')}</p></div>
                                    <div className="appointments-list">
                                        <h4>Consultas para {selectedDay.format('DD/MM')}</h4>
                                        {showSpinner ? <Spinner /> : (DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]?.filter(app => MedicoFiltrado.id === "vazio" || app.doctor_id === MedicoFiltrado.id).length > 0) ? (
                                            DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')]
                                                .filter(app => MedicoFiltrado.id === "vazio" || app.doctor_id === MedicoFiltrado.id)
                                                .map(app => (
                                                    <div key={app.id} className="appointment-item" data-status={app.status}>
                                                        <div className="item-time">{dayjs(app.scheduled_at).format('HH:mm')}</div>
                                                        <div className="item-details"><span>{app.paciente_nome}</span><small>Dr(a). {app.medico_nome}</small></div>
                                                        <div className="appointment-actions">
                                                            {app.status === 'cancelled' ? (
                                                                <button className="btn-action btn-edit" onClick={() => { setSelectedId(app.id); confirmConsulta(app.id); }}>
                                                                    <CheckCircle size={16} title="Reverter Cancelamento" />
                                                                </button>
                                                            ) : (
                                                                <button 
                                                                    className="btn-action btn-edit" 
                                                                    onClick={() => handleEditConsulta(app)} 
                                                                    title="Editar Agendamento"
                                                                >
                                                                    <Edit size={16} />
                                                                </button>
                                                            )}
                                                            {app.status !== 'cancelled' && (
                                                                <button className="btn-action btn-delete" onClick={() => { setSelectedId(app.id); setShowDeleteModal(true); }} title="Cancelar Agendamento">
                                                                    <Trash2 size={16} />
                                                                </button>
                                                            )}
                                                        </div>
                                                    </div>
                                                ))
                                        ) : (<div className="no-appointments-info"><p>Nenhuma consulta agendada.</p></div>)}
                                    </div>
                                </div>
                                <div className="calendar-main">
                                    <div className="calendar-legend">
                                        <div className="legend-item" data-status="completed">Realizado</div>
                                        <div className="legend-item" data-status="confirmed">Confirmado</div>
                                        <div className="legend-item" data-status="agendado">Agendado</div>
                                        <div className="legend-item" data-status="cancelled">Cancelado</div>
                                    </div>
                                    <div className="calendar-controls">
                                        <div className="date-indicator">
                                            <h2>{currentDate.format('MMMM [de] YYYY')}</h2>
                                            <div className="quick-jump-controls" style={{ display: 'flex', gap: '5px', marginTop: '10px' }}>
                                                <select
                                                    value={quickJump.month}
                                                    onChange={(e) => handleQuickJumpChange('month', e.target.value)}
                                                    className="form-select form-select-sm w-auto"
                                                >
                                                    {dayjs.months().map((month, index) => (
                                                        <option key={index} value={index}>{month.charAt(0).toUpperCase() + month.slice(1)}</option>
                                                    ))}
                                                </select>
                                                <select
                                                    value={quickJump.year}
                                                    onChange={(e) => handleQuickJumpChange('year', e.target.value)}
                                                    className="form-select form-select-sm w-auto"
                                                >
                                                    {Array.from({ length: 11 }, (_, i) => dayjs().year() - 5 + i).map(year => (
                                                        <option key={year} value={year}>{year}</option>
                                                    ))}
                                                </select>
                                                <button
                                                    className="btn btn-sm btn-outline-primary"
                                                    onClick={applyQuickJump}
                                                    disabled={quickJump.month === currentDate.month() && quickJump.year === currentDate.year()}
                                                >
                                                    Ir
                                                </button>
                                            </div>
                                        </div>
                                        <div className="nav-buttons">
                                            <button onClick={() => { setCurrentDate(currentDate.subtract(1, 'month')); setSelectedDay(currentDate.subtract(1, 'month')); }}><ChevronLeft size={20} /></button>
                                            <button onClick={() => { setCurrentDate(dayjs()); setSelectedDay(dayjs()); }}>Hoje</button>
                                            <button onClick={() => { setCurrentDate(currentDate.add(1, 'month')); setSelectedDay(currentDate.add(1, 'month')); }}><ChevronRight size={20} /></button>
                                        </div>
                                    </div>
                                    <div className="calendar-grid">
                                        {weekDays.map(day => <div key={day} className="day-header">{day}</div>)}
                                        {dateGrid.map((day, index) => {
                                            const dayString = day.format('YYYY-MM-DD');
                                            const appointmentsOnDay = DictAgendamentosOrganizados[dayString] || [];
                                            const filteredAppointments = appointmentsOnDay.filter(app => MedicoFiltrado.id === "vazio" || app.doctor_id === MedicoFiltrado.id);
                                            const cellClasses = `day-cell ${day.isSame(currentDate, 'month') ? 'current-month' : 'other-month'} ${day.isSame(dayjs(), 'day') ? 'today' : ''} ${day.isSame(selectedDay, 'day') ? 'selected' : ''}`;
                                            return (
                                                <div key={index} className={cellClasses} onClick={() => handleDateClick(day)}>
                                                    <span>{day.format('D')}</span>
                                                    {filteredAppointments.length > 0 && <div className="appointments-indicator">{filteredAppointments.length}</div>}
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="page-content table-paciente-container">
                                <section className="row">
                                    <div className="col-12">
                                        <div className="card table-paciente-card">
                                            <div className="card-header"><h4 className="card-title mb-0">Fila de Espera</h4></div>
                                            <div className="card-body">
                                                <div className="card p-3 mb-3 table-paciente-filters">
                                                    <h5 className="mb-3"><i className="bi bi-funnel-fill me-2 text-primary"></i> Filtros</h5>
                                                    <div className="mb-3"><input type="text" className="form-control" placeholder="Buscar por paciente, CPF ou médico..." value={waitlistSearch} onChange={(e) => setWaitlistSearch(e.target.value)} /><small className="text-muted">Digite o nome do paciente, CPF ou nome do médico</small></div>
                                                    <div className="d-flex flex-wrap align-items-center gap-2 mb-3">
                                                        <div className="d-flex align-items-center gap-2">
                                                            <span className="me-2 text-muted small">Ordenar por:</span>
                                                            <select
                                                                className="form-select compact-select sort-select w-auto"
                                                                value={waitSortKey ? `${waitSortKey}-${waitSortDir}` : ''}
                                                                onChange={(e) => {
                                                                    const v = e.target.value;
                                                                    if (!v) { setWaitSortKey(null); setWaitSortDir('asc'); return; }
                                                                    const [k, d] = v.split('-');
                                                                    setWaitSortKey(k);
                                                                    setWaitSortDir(d);
                                                                }}
                                                            >
                                                                <option value="">Sem ordenação</option>
                                                                <option value="paciente-asc">Paciente (A-Z)</option>
                                                                <option value="paciente-desc">Paciente (Z-A)</option>
                                                                <option value="medico-asc">Médico (A-Z)</option>
                                                                <option value="medico-desc">Médico (Z-A)</option>
                                                                <option value="data-asc">Data (mais antiga)</option>
                                                                <option value="data-desc">Data (mais recente)</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div className="mt-3">
                                                        <div className="contador-pacientes">{filaEsperaFiltrada.length} DE {filaEsperaData.length} SOLICITAÇÕES ENCONTRADAS</div>
                                                    </div>
                                                </div>
                                                <div className="table-responsive">
                                                    <table className="table table-striped table-hover table-paciente-table">
                                                        <thead>
                                                            <tr>
                                                                <th>Nome do Paciente</th>
                                                                <th>CPF</th>
                                                                <th>Médico Solicitado</th>
                                                                <th>Data da Solicitação</th>
                                                                <th>Ações</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            {filaEsperaPaginada.length > 0 ? (
                                                                filaEsperaPaginada.map((item, index) => (
                                                                    <tr key={index}>
                                                                        <td>{item?.Infos?.paciente_nome}</td>
                                                                        <td>{item?.Infos?.paciente_cpf}</td>
                                                                        <td>{item?.Infos?.medico_nome}</td>
                                                                        <td>{dayjs(item.agendamento.scheduled_at).format('DD/MM/YYYY')}</td>
                                                                        <td>
                                                                            <button className="btn btn-sm btn-delete" onClick={() => { setSelectedId(item.agendamento.id); setShowDeleteModal(true); }}>
                                                                                <i className="bi bi-trash me-1"></i> Excluir
                                                                            </button>
                                                                        </td>
                                                                    </tr>
                                                                ))
                                                            ) : (
                                                                <tr>
                                                                    <td colSpan="5" className="text-center py-4">
                                                                        <div className="text-muted">
                                                                            {showSpinner ? <Spinner /> : (<><i className="bi bi-inbox display-4"></i><p className="mt-2">Nenhuma solicitação encontrada.</p></>)}
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            )}
                                                        </tbody>
                                                    </table>
                                                    {filaEsperaFiltrada.length > 0 && (
                                                        <div className="d-flex justify-content-between align-items-center mt-3">
                                                            <div className="d-flex align-items-center">
                                                                <span className="me-2 text-muted">Itens por página:</span>
                                                                <select
                                                                    className="form-select form-select-sm w-auto"
                                                                    value={waitPerPage}
                                                                    onChange={(e) => { setWaitPerPage(Number(e.target.value)); setWaitPage(1); }}
                                                                >
                                                                    <option value={5}>5</option>
                                                                    <option value={10}>10</option>
                                                                    <option value={25}>25</option>
                                                                    <option value={50}>50</option>
                                                                </select>
                                                            </div>
                                                            <div className="d-flex align-items-center">
                                                                <span className="me-3 text-muted">Página {waitPage} de {waitTotalPages} • Mostrando {waitIndiceInicial + 1}-{Math.min(waitIndiceFinal, filaEsperaFiltrada.length)} de {filaEsperaFiltrada.length}</span>
                                                                <nav>
                                                                    <ul className="pagination pagination-sm mb-0">
                                                                        <li className={`page-item ${waitPage === 1 ? 'disabled' : ''}`}>
                                                                            <button className="page-link" onClick={() => setWaitPage(p => Math.max(1, p - 1))}>
                                                                                <i className="bi bi-chevron-left"></i>
                                                                            </button>
                                                                        </li>
                                                                        {gerarNumerosWaitPages().map(pagina => (
                                                                            <li key={pagina} className={`page-item ${pagina === waitPage ? 'active' : ''}`}>
                                                                                <button className="page-link" onClick={() => setWaitPage(pagina)}>{pagina}</button>
                                                                            </li>
                                                                        ))}
                                                                        <li className={`page-item ${waitPage === waitTotalPages ? 'disabled' : ''}`}>
                                                                            <button className="page-link" onClick={() => setWaitPage(p => Math.min(waitTotalPages, p + 1))}>
                                                                                <i className="bi bi-chevron-right"></i>
                                                                            </button>
                                                                        </li>
                                                                    </ul>
                                                                </nav>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </section>
                            </div>
                        )}
                    </section>
                </div>
            ) : (
                <AgendamentoCadastroManager 
                    setPageConsulta={setPageConsulta} 
                    agendamentoInicial={agendamentoParaEdicao} 
                    onSuccess={() => {
                        setPageConsulta(false);
                        fetchAppointments();
                    }}
                />
            )}
            {showDeleteModal && <DeleteModal />}
        </div>
    );
}

export default Agendamento;
