// Calendar Page
let calendarInstance = null;

async function renderCalendar() {
    const content = document.getElementById('main-content');
    
    content.innerHTML = `
        <div class="space-y-6">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <h3 class="text-xl font-semibold text-gray-800 dark:text-white">Agenda</h3>
                <button onclick="openEventModal()" class="btn-primary" data-testid="button-new-event">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    Novo Evento
                </button>
            </div>
            
            <!-- Legend -->
            <div id="calendar-legend" class="flex flex-wrap gap-4 text-sm">
                <!-- Admin colors will be loaded here -->
            </div>
            
            <div class="card p-4">
                <div id="calendar-container" style="min-height: 600px;"></div>
            </div>
        </div>
    `;
    
    try {
        const administrators = await apiRequest('administrators.php');
        window.calendarAdmins = administrators;
        
        const legendDiv = document.getElementById('calendar-legend');
        legendDiv.innerHTML = administrators.filter(a => a.active).map(admin => `
            <div class="flex items-center gap-2">
                <div class="w-4 h-4 rounded-full" style="background-color: ${admin.color}"></div>
                <span class="text-gray-600 dark:text-gray-400">${admin.name}</span>
            </div>
        `).join('');
        
        initCalendar();
        
    } catch (error) {
        content.innerHTML = `<div class="text-red-500">Erro ao carregar agenda: ${error.message}</div>`;
    }
}

function initCalendar() {
    const calendarEl = document.getElementById('calendar-container');
    
    if (calendarInstance) {
        calendarInstance.destroy();
    }
    
    calendarInstance = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        locale: 'pt-br',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
        },
        buttonText: {
            today: 'Hoje',
            month: 'Mês',
            week: 'Semana',
            day: 'Dia',
            list: 'Lista'
        },
        events: async function(info, successCallback, failureCallback) {
            try {
                const start = info.start.toISOString();
                const end = info.end.toISOString();
                const events = await apiRequest(`calendar.php?start=${start}&end=${end}`);
                
                const formattedEvents = events.map(event => ({
                    id: event.id,
                    title: event.title,
                    start: event.start_date,
                    end: event.end_date || event.start_date,
                    allDay: event.all_day,
                    backgroundColor: event.admin_color || '#3B82F6',
                    borderColor: event.admin_color || '#3B82F6',
                    extendedProps: {
                        description: event.description,
                        createdBy: event.created_by_name,
                        createdById: event.created_by
                    }
                }));
                
                successCallback(formattedEvents);
            } catch (error) {
                console.error('Error loading events:', error);
                failureCallback(error);
            }
        },
        eventClick: function(info) {
            showEventDetails(info.event);
        },
        dateClick: function(info) {
            openEventModal(null, info.dateStr);
        },
        eventDidMount: function(info) {
            info.el.style.cursor = 'pointer';
        },
        editable: false,
        selectable: true,
        selectMirror: true,
        dayMaxEvents: true,
        height: 'auto'
    });
    
    calendarInstance.render();
}

function showEventDetails(event) {
    const canEdit = event.extendedProps.createdById === currentUser?.id;
    
    const modalContent = `
        <div class="p-6">
            <div class="flex items-start justify-between mb-4">
                <div class="flex items-center gap-3">
                    <div class="w-4 h-4 rounded-full" style="background-color: ${event.backgroundColor}"></div>
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white">${event.title}</h3>
                </div>
            </div>
            
            <div class="space-y-3">
                <div>
                    <span class="text-sm text-gray-500">Data/Hora:</span>
                    <p class="text-gray-800 dark:text-white">
                        ${event.allDay ? formatDate(event.startStr) : formatDateTime(event.startStr)}
                        ${event.end ? ' - ' + (event.allDay ? formatDate(event.endStr) : formatDateTime(event.endStr)) : ''}
                    </p>
                </div>
                
                ${event.extendedProps.description ? `
                    <div>
                        <span class="text-sm text-gray-500">Descrição:</span>
                        <p class="text-gray-800 dark:text-white">${event.extendedProps.description}</p>
                    </div>
                ` : ''}
                
                <div>
                    <span class="text-sm text-gray-500">Criado por:</span>
                    <p class="text-gray-800 dark:text-white">${event.extendedProps.createdBy || 'Desconhecido'}</p>
                </div>
            </div>
            
            <div class="flex justify-end gap-3 pt-6">
                <button onclick="closeModal()" class="btn-secondary">Fechar</button>
                ${canEdit ? `
                    <button onclick="openEventModal('${event.id}')" class="btn-primary">Editar</button>
                    <button onclick="deleteEvent('${event.id}')" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md">Excluir</button>
                ` : ''}
            </div>
        </div>
    `;
    
    openModal(modalContent);
}

async function openEventModal(eventId = null, dateStr = null) {
    let event = null;
    
    if (eventId) {
        try {
            event = await apiRequest(`calendar.php?id=${eventId}`);
        } catch (error) {
            showToast('Erro ao carregar evento', 'error');
            return;
        }
    }
    
    const today = new Date().toISOString().slice(0, 16);
    const defaultDate = dateStr ? dateStr + 'T09:00' : today;
    
    const modalContent = `
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">${eventId ? 'Editar' : 'Novo'} Evento</h3>
            <form id="event-form" class="space-y-4">
                <input type="hidden" id="event-id" value="${eventId || ''}">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Título *</label>
                    <input type="text" id="event-title" required class="form-input" value="${event?.title || ''}" data-testid="input-event-title">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Descrição</label>
                    <textarea id="event-description" class="form-input" rows="3" data-testid="input-event-description">${event?.description || ''}</textarea>
                </div>
                
                <div class="flex items-center gap-2">
                    <input type="checkbox" id="event-allday" class="w-4 h-4 rounded" ${event?.all_day ? 'checked' : ''} onchange="toggleDateTimeInputs()">
                    <label for="event-allday" class="text-sm text-gray-700 dark:text-gray-300">Dia inteiro</label>
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Início *</label>
                        <input type="${event?.all_day ? 'date' : 'datetime-local'}" id="event-start" required class="form-input" value="${event?.start_date?.slice(0, event.all_day ? 10 : 16) || defaultDate}" data-testid="input-event-start">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Fim</label>
                        <input type="${event?.all_day ? 'date' : 'datetime-local'}" id="event-end" class="form-input" value="${event?.end_date?.slice(0, event?.all_day ? 10 : 16) || ''}" data-testid="input-event-end">
                    </div>
                </div>
                
                <div class="flex justify-end gap-3 pt-4">
                    <button type="button" onclick="closeModal()" class="btn-secondary">Cancelar</button>
                    <button type="submit" class="btn-primary" data-testid="button-save-event">Salvar</button>
                </div>
            </form>
        </div>
    `;
    
    openModal(modalContent);
    
    document.getElementById('event-form').onsubmit = async (e) => {
        e.preventDefault();
        await saveEvent();
    };
}

function toggleDateTimeInputs() {
    const allDay = document.getElementById('event-allday').checked;
    const startInput = document.getElementById('event-start');
    const endInput = document.getElementById('event-end');
    
    const startValue = startInput.value;
    const endValue = endInput.value;
    
    if (allDay) {
        startInput.type = 'date';
        endInput.type = 'date';
        startInput.value = startValue.slice(0, 10);
        endInput.value = endValue ? endValue.slice(0, 10) : '';
    } else {
        startInput.type = 'datetime-local';
        endInput.type = 'datetime-local';
        startInput.value = startValue.length === 10 ? startValue + 'T09:00' : startValue;
        endInput.value = endValue && endValue.length === 10 ? endValue + 'T10:00' : endValue;
    }
}

async function saveEvent() {
    const id = document.getElementById('event-id').value;
    const allDay = document.getElementById('event-allday').checked;
    
    let startDate = document.getElementById('event-start').value;
    let endDate = document.getElementById('event-end').value;
    
    if (allDay) {
        startDate = startDate + 'T00:00:00';
        endDate = endDate ? endDate + 'T23:59:59' : null;
    }
    
    const data = {
        title: document.getElementById('event-title').value,
        description: document.getElementById('event-description').value || null,
        start_date: startDate,
        end_date: endDate,
        all_day: allDay
    };
    
    try {
        if (id) {
            await apiRequest(`calendar.php?id=${id}`, 'PUT', data);
            showToast('Evento atualizado com sucesso!');
        } else {
            await apiRequest('calendar.php', 'POST', data);
            showToast('Evento criado com sucesso!');
        }
        closeModal();
        if (calendarInstance) {
            calendarInstance.refetchEvents();
        }
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deleteEvent(id) {
    if (!confirm('Tem certeza que deseja excluir este evento?')) return;
    
    try {
        await apiRequest(`calendar.php?id=${id}`, 'DELETE');
        showToast('Evento excluído com sucesso!');
        closeModal();
        if (calendarInstance) {
            calendarInstance.refetchEvents();
        }
    } catch (error) {
        showToast(error.message, 'error');
    }
}
