import React, { useMemo } from 'react';
import dayjs from 'dayjs';
import { ChevronLeft, ChevronRight, Edit, Trash2 } from 'lucide-react';
import Spinner from '../Spinner.jsx'; // Certifique-se de que o caminho está correto

const CalendarComponent = ({
    currentDate,
    setCurrentDate,
    selectedDay,
    setSelectedDay,
    DictAgendamentosOrganizados,
    showSpinner,
    setSelectedId,
    setShowDeleteModal,
    setShowConfirmModal,
    quickJump,
    handleQuickJumpChange,
    applyQuickJump
}) => {
    
    // Gera os 42 dias para o grid do calendário
    const generateDateGrid = () => {
        const grid = []; 
        const startOfMonth = currentDate.startOf('month');
        // Começa no domingo da semana em que o mês começa (day() retorna 0 para domingo)
        let currentDay = startOfMonth.subtract(startOfMonth.day(), 'day'); 

        // Gera 6 semanas (6*7 = 42 dias)
        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);
        // Opcional: Adicionar lógica para abrir o agendamento do dia/semana/mês (sua primeira imagem)
        // Se você quiser que o clique abra a tela de agendamento de slots:
        // Exemplo: onSelectDate(day);
    };

    // Função para obter o status de agendamentos para o indicador (ponto azul)
    const getAppointmentCount = (day) => {
        return DictAgendamentosOrganizados[day.format('YYYY-MM-DD')]?.length || 0;
    };

    return (
        <div className="calendar-wrapper">
            {/* Painel lateral de informações */}
            <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')]?.length > 0) ? (
                        DictAgendamentosOrganizados[selectedDay.format('YYYY-MM-DD')].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); setShowConfirmModal(true); }}>
                                            <Edit size={16} />
                                        </button>
                                    ) : (
                                        <button className="btn-action btn-delete" onClick={() => { setSelectedId(app.id); setShowDeleteModal(true); }}>
                                            <Trash2 size={16} />
                                        </button>
                                    )}
                                </div>
                            </div>
                        ))
                    ) : (
                        <div className="no-appointments-info"><p>Nenhuma consulta agendada.</p></div>
                    )}
                </div>
            </div>

            {/* Calendário Principal */}
            <div className="calendar-main">
                {/* Legenda */}
                <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>

                {/* Controles de navegação e Jump */}
                <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>
                
                {/* Grid dos dias */}
                <div className="calendar-grid">
                    {weekDays.map(day => <div key={day} className="day-header">{day}</div>)}
                    {dateGrid.map((day, index) => {
                        const count = getAppointmentCount(day);
                        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>
                                {count > 0 && <div className="appointments-indicator">{count}</div>}
                            </div>
                        );
                    })}
                </div>
            </div>
        </div>
    );
};

export default CalendarComponent;