import React, { useState, useMemo, useEffect } from 'react';
import dayjs from 'dayjs';
import CalendarComponent from '../components/AgendarConsulta/CalendarComponent.jsx'; 
import { useAuth } from '../components/utils/AuthProvider.js'; 
import TabelaAgendamentoDia from '../components/AgendarConsulta/TabelaAgendamentoDia'; 

dayjs.locale('pt-br');

const MedicoAgendamento = () => {
    const { getAuthorizationHeader, user } = useAuth(); 
    const [currentDate, setCurrentDate] = useState(dayjs());
    const [selectedDay, setSelectedDay] = useState(dayjs());
    const [DictAgendamentosOrganizados, setAgendamentosOrganizados] = useState({});
    const [showSpinner, setShowSpinner] = useState(true);
    const [modoVisualizacao, setModoVisualizacao] = useState('Dia'); 
    
  
    const [quickJump, setQuickJump] = useState({ 
        month: currentDate.month(), 
        year: currentDate.year() 
    });

    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); 
    };

   
    const [selectedID, setSelectedId] = useState('0'); 
    const [showDeleteModal, setShowDeleteModal] = useState(false); 
    const [showConfirmModal, setShowConfirmModal] = useState(false); t
    
   
    useEffect(() => {
       
        const mockAgendamentos = {
            [dayjs().format('YYYY-MM-DD')]: [
                { id: 1, scheduled_at: dayjs().set('hour', 10).set('minute', 0).toISOString(), paciente_nome: "Paciente Teste 1", medico_nome: "Dr. Mock", status: "agendado" },
                { id: 2, scheduled_at: dayjs().set('hour', 11).set('minute', 30).toISOString(), paciente_nome: "Paciente Teste 2", medico_nome: "Dr. Mock", status: "confirmed" },
            ],
          
            '2025-10-27': [ 
                { id: 3, scheduled_at: '2025-10-27T19:30:00Z', paciente_nome: 'Davi Andrade', medico_nome: 'Dr. João', status: 'agendado' },
                { id: 4, scheduled_at: '2025-10-27T20:00:00Z', paciente_nome: 'Davi Andrade', medico_nome: 'Dr. João', status: 'agendado' },
                { id: 5, scheduled_at: '2025-10-27T21:30:00Z', paciente_nome: 'Davi Andrade', medico_nome: 'Dr. João', status: 'agendado' },
            ]
        };

        const today = dayjs();
        const startOfMonth = today.startOf('month');
        const nov11 = startOfMonth.add(10, 'day').format('YYYY-MM-DD'); 
        
      
        mockAgendamentos[nov11] = [
             { id: 6, scheduled_at: `${nov11}T10:30:00Z`, paciente_nome: 'Paciente C', medico_nome: 'Isaac Kauã', status: 'agendado' },
             { id: 7, scheduled_at: `${nov11}T11:00:00Z`, paciente_nome: 'João Gustavo', medico_nome: 'João Gustavo', status: 'agendado' },
             { id: 8, scheduled_at: `${nov11}T12:30:00Z`, paciente_nome: 'João Gustavo', medico_nome: 'João Gustavo', status: 'agendado' },
             { id: 9, scheduled_at: `${nov11}T15:00:00Z`, paciente_nome: 'Pedro Abravanel', medico_nome: 'Fernando Prichowski', status: 'agendado' },
        ];


        setAgendamentosOrganizados(mockAgendamentos);
        setShowSpinner(false);
    }, []); 

   
    const handleSelectSlot = (timeSlot, doctorId) => {
        alert(`Abrir tela de Nova Consulta para o dia ${selectedDay.format('DD/MM/YYYY')} às ${timeSlot} com o Médico ID: ${doctorId}`);
        
    };

    const isMedico = true; 
    const medicoLogadoID = user?.doctor_id || "ID_MEDICO_DEFAULT"; 

    return (
        <div className='agendamento-medico-container'>
            <h1>Agenda do Médico: {user?.full_name || "Nome do Médico"}</h1>
            <div className="btns-gerenciamento-e-consulta" style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
                <button className='manage-button btn' onClick={() => {}}><i className="bi bi-gear-fill me-1"></i> Mudar Disponibilidade</button>
                <button className="btn btn-primary" onClick={() => {}}><i className="bi bi-person-plus-fill"></i> Adicionar Paciente</button>
            </div>
            
            <div className="tab-buttons" style={{ marginBottom: '20px' }}>
                <button className={`btn ${modoVisualizacao === 'Dia' ? 'btn-primary' : 'btn-outline-primary'}`} onClick={() => setModoVisualizacao('Dia')}>Dia</button>
                <button className={`btn ${modoVisualizacao === 'Semana' ? 'btn-primary' : 'btn-outline-primary'}`} onClick={() => setModoVisualizacao('Semana')}>Semana</button>
                <button className={`btn ${modoVisualizacao === 'Mês' ? 'btn-primary' : 'btn-outline-primary'}`} onClick={() => setModoVisualizacao('Mês')}>Mês</button>
            </div>

            <div className='agenda-e-calendario-wrapper'>
                {}
                <div className='medico-calendar-column' style={{ flex: 1 }}>
                    <CalendarComponent
                        currentDate={currentDate}
                        setCurrentDate={setCurrentDate}
                        selectedDay={selectedDay}
                        setSelectedDay={setSelectedDay}
                        DictAgendamentosOrganizados={DictAgendamentosOrganizados}
                        showSpinner={showSpinner}
                       T
                        setSelectedId={setSelectedId} 
                        setShowDeleteModal={setShowDeleteModal} 
                        setShowConfirmModal={setShowConfirmModal}
                        quickJump={quickJump}
                        handleQuickJumpChange={handleQuickJumpChange}
                        applyQuickJump={applyQuickJump}
                    />
                </div>

                {}
                <div className='medico-schedule-column' style={{ flex: 2 }}>
                    {modoVisualizacao === 'Dia' && (
                        <TabelaAgendamentoDia 
                            selectedDay={selectedDay} 
                            agendamentosDoDia={DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')] || []}
                            onSelectSlot={handleSelectSlot}
                            isMedicoView={isMedico} 
                            medicoID={medicoLogadoID} 
                            horariosDeTrabalho={[
                                { hora: '19:30', medicoId: '123' }, 
                                { hora: '20:00', medicoId: '123' }, 
                                { hora: '21:30', medicoId: '123' }
                            ]}
                        />
                    )}
                    {}
                    {}
                    {}
                </div>
            </div>
        </div>
    );
};

export default MedicoAgendamento;