/**
 * ================================================
 * ESTREKA KALENDRI MEELDETULETUSTE SÜSTEEM - WIZARD INTEGRATSIOONIGA
 * ================================================
 * 
 * FUNKTSIOONID:
 * - Ajutised meeldetuletused (enne sündmuse salvestamist)
 * - Kõik meeldetuletused salvestatakse koos sündmusega
 * - Wizard integratsioon
 * - Olemasolev funktsinaalsus säilib
 * - UUENDATUD: Detailsem info kuvamine
 * 
 * ================================================
 */

// Globaalsed muutujad meeldetuletuste jaoks
let currentEventReminders = [];
let temporaryReminders = [];
let isEditingReminder = false;
let reminderIdCounter = 1;

// ==========================================
// MEELDETULETUSTE LAADIMINE
// ==========================================

async function loadEventReminders(eventId) {
    if (!eventId) {
        currentEventReminders = [];
        temporaryReminders = [];
        renderReminders();
        return;
    }
    
    try {
        debugLog('Laadin sündmuse meeldetuletusi:', eventId);
        
        const response = await fetch(`${API_BASE_URL}reminders.php?action=event&event_id=${eventId}`);
        const result = await response.json();
        
        if (result.success) {
            currentEventReminders = result.data || [];
            temporaryReminders = [];
            debugLog('Meeldetuletused laaditud:', currentEventReminders.length);
            renderReminders();
        } else {
            console.warn('Meeldetuletuste laadimine:', result.error);
            currentEventReminders = [];
            renderReminders();
        }
        
    } catch (error) {
        console.error('Meeldetuletuste laadimisel tekkis viga:', error);
        currentEventReminders = [];
        renderReminders();
    }
}

// UUENDATUD: Detailsem meeldetuletuste kuvamine
function renderReminders() {
    const container = safeGetElement('reminders-list');
    if (!container) return;
    
    const allReminders = [...currentEventReminders, ...temporaryReminders];
    
    if (allReminders.length === 0) {
        container.innerHTML = `
            <div class="empty-reminders">
                <div style="font-size: 32px; margin-bottom: 8px;">🔔</div>
                <div>Meeldetuletusi pole veel lisatud</div>
                <small style="color: var(--gray-500);">Lisa meeldetuletus üleval oleva nupuga</small>
            </div>
        `;
        return;
    }
    
    container.innerHTML = allReminders.map(reminder => {
        const isTemporary = reminder.isTemporary || false;
        
        // PARANDATUD: Arvuta täpne meeldetuletuse aeg
let reminderTimeInfo = '';
let exactReminderTime = '';

if (reminder.exact_time) {
    // Kui on kasutatud exact_time (kasutaja seadistas täpse kellaaja)
    exactReminderTime = formatReminderTime(reminder.exact_time);
    reminderTimeInfo = `📅 <span class="time-info">Täpne aeg: ${exactReminderTime}</span>`;
} else if (reminder.reminder_datetime) {
    // Kui on olemas reminder_datetime (arvutatud aeg)
    exactReminderTime = formatReminderTime(reminder.reminder_datetime);
    reminderTimeInfo = `📅 <span class="time-info">Saadetakse: ${exactReminderTime}</span>`;
} else {
    // Fallback - ainult minutid enne
    reminderTimeInfo = `⏰ ${reminder.minutes_before || 60} minutit enne sündmust`;
}

// UUENDATUD: Korduvuse info
let recurringInfo = '';
if (reminder.is_recurring) {
    const typeNames = {
        'daily': 'päev',
        'weekly': 'nädal', 
        'monthly': 'kuu'
    };
    const typeName = typeNames[reminder.recurring_type] || reminder.recurring_type || 'päev';
    const interval = reminder.recurring_interval || 1;
    
    if (interval == 1) {
        recurringInfo = `🔄 <span class="recurring-info">Iga ${typeName}</span>`;
    } else {
        recurringInfo = `🔄 <span class="recurring-info">Iga ${interval} ${typeName}</span>`;
    }
    
    if (reminder.recurring_end_date) {
        recurringInfo += ` <small>(kuni ${formatDate(reminder.recurring_end_date)})</small>`;
    }
}
        
        // UUENDATUD: Status info
        let statusInfo = '';
        if (isTemporary) {
            statusInfo = '<span class="status-badge pending">Ajutine</span>';
        } else if (reminder.sent_at) {
            statusInfo = `<span class="status-badge sent">Saadetud ${formatReminderTime(reminder.sent_at)}</span>`;
        } else if (reminder.is_pending) {
            statusInfo = '<span class="status-badge pending">Ootel saatmist</span>';
        } else if (reminder.last_error) {
            statusInfo = '<span class="status-badge failed">Viga saatmisel</span>';
        }
        
        return `
            <div class="reminder-item ${reminder.is_recurring ? 'recurring' : ''} ${isTemporary ? 'temporary' : ''}" data-reminder-id="${reminder.id}">
                <div class="reminder-content">
                    <div class="reminder-text">
                        💬 ${escapeHtml(reminder.custom_message)}
                    </div>
                    <div class="reminder-details">
                        <div class="reminder-timing">
                            ${reminderTimeInfo}
                        </div>
                        ${recurringInfo ? `<div class="reminder-recurring">${recurringInfo}</div>` : ''}
                        ${statusInfo ? `<div class="reminder-status">${statusInfo}</div>` : ''}
                        ${reminder.last_error ? `<div class="reminder-error">❌ Viga: ${reminder.last_error}</div>` : ''}
                    </div>
                </div>
                <div class="reminder-actions">
                    <button class="btn btn-secondary btn-sm" onclick="${isTemporary ? 'editTemporaryReminder' : 'editReminder'}(${reminder.id})" title="Muuda">
                        ✏️
                    </button>
                    <button class="btn btn-danger btn-sm" onclick="${isTemporary ? 'deleteTemporaryReminder' : 'deleteReminder'}(${reminder.id})" title="Kustuta">
                        🗑️
                    </button>
                </div>
            </div>
        `;
    }).join('');
}

// UUENDATUD: Parem kuupäeva formaatimine
function formatReminderTime(datetime) {
    if (!datetime) return '';
    
    const date = new Date(datetime);
    if (isNaN(date.getTime())) return '';
    
    const now = new Date();
    const isToday = date.toDateString() === now.toDateString();
    const isTomorrow = date.toDateString() === new Date(now.getTime() + 24*60*60*1000).toDateString();
    
    let dateStr = '';
    if (isToday) {
        dateStr = 'täna';
    } else if (isTomorrow) {
        dateStr = 'homme';
    } else {
        dateStr = date.toLocaleDateString('et-EE', { 
            day: '2-digit', 
            month: '2-digit',
            year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined
        });
    }
    
    const timeStr = date.toLocaleTimeString('et-EE', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    return `${dateStr} ${timeStr}`;
}

// UUENDATUD: Lisa kuupäeva formaatimise helper
function formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    
    return date.toLocaleDateString('et-EE', { 
        day: '2-digit', 
        month: '2-digit', 
        year: 'numeric' 
    });
}

// ==========================================
// AJUTISTE MEELDETULETUSTE HALDUS
// ==========================================

function addTemporaryReminder(reminderData) {
    const tempReminder = {
        id: reminderIdCounter++,
        isTemporary: true,
        custom_message: reminderData.custom_message,
        minutes_before: reminderData.minutes_before || 60,
        is_recurring: reminderData.is_recurring || false,
        recurring_type: reminderData.recurring_type || null,
        recurring_interval: reminderData.recurring_interval || 1,
        recurring_end_date: reminderData.recurring_end_date || null,
        exact_time: reminderData.exact_time || null,
        formatted_reminder_time: reminderData.exact_time ? 
            new Date(reminderData.exact_time).toLocaleDateString('et-EE') + ' ' + 
            new Date(reminderData.exact_time).toLocaleTimeString('et-EE', { hour: '2-digit', minute: '2-digit' }) :
            `${reminderData.minutes_before || 60} min enne`
    };
    
    temporaryReminders.push(tempReminder);
    renderReminders();
    
    debugLog('Ajutine meeldetuletus lisatud:', tempReminder);
    return tempReminder;
}

function editTemporaryReminder(tempId) {
    const reminder = temporaryReminders.find(r => r.id === tempId);
    if (!reminder) {
        showNotification('Ajutist meeldetuletust ei leitud', 'error');
        return;
    }
    
    fillReminderModal(reminder, true);
    isEditingReminder = true;
    openReminderModal();
}

function deleteTemporaryReminder(tempId) {
    const index = temporaryReminders.findIndex(r => r.id === tempId);
    if (index === -1) {
        showNotification('Ajutist meeldetuletust ei leitud', 'error');
        return;
    }
    
    const confirmed = confirm(`Kas oled kindel, et soovid kustutada ajutise meeldetuletuse:\n"${temporaryReminders[index].custom_message}"?`);
    if (!confirmed) return;
    
    temporaryReminders.splice(index, 1);
    renderReminders();
    showNotification('Ajutine meeldetuletus kustutatud!', 'success');
}

async function saveTemporaryReminders(eventId) {
    if (temporaryReminders.length === 0) {
        debugLog('Ajutisi meeldetuletusi pole salvestamiseks');
        return true;
    }
    
    debugLog('Salvestan ajutised meeldetuletused:', temporaryReminders.length);
    
    let successCount = 0;
    let errorCount = 0;
    
    for (const tempReminder of temporaryReminders) {
        try {
            const reminderData = {
                event_id: eventId,
                custom_message: tempReminder.custom_message,
                minutes_before: tempReminder.minutes_before,
                is_recurring: tempReminder.is_recurring,
                recurring_type: tempReminder.recurring_type,
                recurring_interval: tempReminder.recurring_interval,
                recurring_end_date: tempReminder.recurring_end_date,
                exact_time: tempReminder.exact_time
            };
            
            const response = await fetch(`${API_BASE_URL}reminders.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(reminderData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                successCount++;
                debugLog('Ajutine meeldetuletus salvestatud:', tempReminder.custom_message);
            } else {
                errorCount++;
                console.error('Ajutise meeldetuletuse salvestamine ebaõnnestus:', result.error);
            }
            
        } catch (error) {
            errorCount++;
            console.error('Viga ajutise meeldetuletuse salvestamisel:', error);
        }
    }
    
    temporaryReminders = [];
    
    if (successCount > 0) {
        showNotification(`${successCount} meeldetuletust salvestatud!`, 'success');
    }
    
    if (errorCount > 0) {
        showNotification(`${errorCount} meeldetuletuse salvestamine ebaõnnestus`, 'warning');
    }
    
    return errorCount === 0;
}

// ==========================================
// DETAILSE MEELDETULETUSE MODAL
// ==========================================

function addReminder() {
    const eventId = safeGetElement('event-id')?.value;
    
    if (!eventId) {
        showNotification('Meeldetuletus salvestatakse koos sündmusega', 'info');
    }
    
    resetReminderForm();
    const reminderEventId = safeGetElement('reminder-event-id');
    if (reminderEventId) reminderEventId.value = eventId || '';
    
    const modalTitle = safeGetElement('reminder-modal-title');
    if (modalTitle) modalTitle.textContent = 'Lisa meeldetuletus';
    
    isEditingReminder = false;
    openReminderModal();
}

function editReminder(reminderId) {
    const reminder = currentEventReminders.find(r => r.id == reminderId);
    if (!reminder) {
        showNotification('Meeldetuletust ei leitud', 'error');
        return;
    }
    
    fillReminderModal(reminder, false);
    isEditingReminder = true;
    openReminderModal();
}

function fillReminderModal(reminder, isTemporary) {
    debugLog('Täidan meeldetuletuse modali:', reminder);
    
    const reminderIdField = safeGetElement('reminder-id');
    const reminderEventIdField = safeGetElement('reminder-event-id');
    const reminderMessageField = safeGetElement('reminder-message');
    const reminderMinutesField = safeGetElement('reminder-minutes');
    
    if (reminderIdField) reminderIdField.value = reminder.id;
    if (reminderEventIdField) reminderEventIdField.value = reminder.event_id || '';
    if (reminderMessageField) reminderMessageField.value = reminder.custom_message;
    if (reminderMinutesField) reminderMinutesField.value = reminder.minutes_before;
    
    const tempFlag = safeGetElement('reminder-is-temporary');
    if (tempFlag) {
        tempFlag.value = isTemporary ? '1' : '0';
    } else {
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.id = 'reminder-is-temporary';
        hiddenInput.value = isTemporary ? '1' : '0';
        const form = safeGetElement('reminder-form');
        if (form) form.appendChild(hiddenInput);
    }
    
    const recurringCheckbox = safeGetElement('reminder-recurring');
    const recurringSettings = safeGetElement('recurring-settings');
    
    if (recurringCheckbox) {
        recurringCheckbox.checked = reminder.is_recurring == 1;
        if (recurringSettings) {
            recurringSettings.style.display = reminder.is_recurring ? 'block' : 'none';
        }
    }
    
    if (reminder.is_recurring) {
        const typeSelect = safeGetElement('recurring-type');
        const intervalSelect = safeGetElement('recurring-interval');
        const endDateInput = safeGetElement('recurring-end');
        
        if (typeSelect) typeSelect.value = reminder.recurring_type || 'daily';
        if (intervalSelect) intervalSelect.value = reminder.recurring_interval || 1;
        if (endDateInput) endDateInput.value = reminder.recurring_end_date || '';
    }
    
    const modalTitle = safeGetElement('reminder-modal-title');
    const deleteBtn = safeGetElement('delete-reminder-btn');
    
    if (modalTitle) modalTitle.textContent = isTemporary ? 'Muuda ajutist meeldetuletust' : 'Muuda meeldetuletust';
    if (deleteBtn) deleteBtn.style.display = 'inline-flex';
}

async function deleteReminder(reminderId) {
    const reminder = currentEventReminders.find(r => r.id == reminderId);
    if (!reminder) {
        showNotification('Meeldetuletust ei leitud', 'error');
        return;
    }
    
    const confirmed = confirm(`Kas oled kindel, et soovid kustutada meeldetuletuse:\n"${reminder.custom_message}"?`);
    if (!confirmed) return;
    
    try {
        debugLog('Kustutan meeldetuletust:', reminderId);
        
        const response = await fetch(`${API_BASE_URL}reminders.php`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: reminderId })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Meeldetuletus kustutatud!', 'success');
            await loadEventReminders(reminder.event_id);
        } else {
            throw new Error(result.error || 'Kustutamine ebaõnnestus');
        }
        
    } catch (error) {
        console.error('Meeldetuletuse kustutamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

async function saveReminder(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    
    const reminderData = {
        custom_message: formData.get('custom_message').trim(),
        is_recurring: formData.get('is_recurring') === 'on'
    };
    
    if (!reminderData.custom_message) {
        showNotification('Sisesta meeldetuletuse tekst', 'warning');
        const messageField = safeGetElement('reminder-message');
        if (messageField) messageField.focus();
        return;
    }
    
    const exactTime = formData.get('exact_time');
    const minutesBefore = formData.get('minutes_before');
    
    // PARANDATUD: Kui on exact_time, siis ära kasuta minutes_before
    if (exactTime && exactTime.trim() !== '') {
        reminderData.exact_time = exactTime;
        debugLog('Kasutan exact_time:', exactTime);
    } else {
        reminderData.minutes_before = parseInt(minutesBefore) || 60;
        debugLog('Kasutan minutes_before:', reminderData.minutes_before);
    }
    
    if (reminderData.is_recurring) {
        reminderData.recurring_type = formData.get('recurring_type') || 'daily';
        reminderData.recurring_interval = parseInt(formData.get('recurring_interval')) || 1;
        reminderData.recurring_end_date = formData.get('recurring_end_date') || null;
    }
    
    const reminderId = formData.get('reminder_id');
    const eventId = formData.get('event_id');
    const isTemporary = formData.get('is_temporary') === '1';
    const isEdit = reminderId && reminderId !== '';
    
    if (isTemporary) {
        const tempIndex = temporaryReminders.findIndex(r => r.id == reminderId);
        if (tempIndex !== -1) {
            temporaryReminders[tempIndex] = {
                ...temporaryReminders[tempIndex],
                ...reminderData,
                formatted_reminder_time: reminderData.exact_time ? 
                    new Date(reminderData.exact_time).toLocaleDateString('et-EE') + ' ' + 
                    new Date(reminderData.exact_time).toLocaleTimeString('et-EE', { hour: '2-digit', minute: '2-digit' }) :
                    `${reminderData.minutes_before || 60} min enne`
            };
            
            renderReminders();
            closeReminderModal();
            showNotification('Ajutine meeldetuletus muudetud!', 'success');
            return;
        }
    }
    
    if (!eventId) {
        addTemporaryReminder(reminderData);
        closeReminderModal();
        showNotification('Ajutine meeldetuletus lisatud! Salvestatakse koos sündmusega.', 'success');
        return;
    }
    
    reminderData.event_id = eventId;
    
    if (isEdit) {
        reminderData.id = reminderId;
    }
    
    try {
        debugLog('Salvestan meeldetuletust:', reminderData);
        
        const response = await fetch(`${API_BASE_URL}reminders.php`, {
            method: isEdit ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(reminderData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification(
                isEdit ? 'Meeldetuletus edukalt muudetud!' : 'Meeldetuletus edukalt lisatud!', 
                'success'
            );
            closeReminderModal();
            await loadEventReminders(reminderData.event_id);
        } else {
            throw new Error(result.error || 'Salvestamine ebaõnnestus');
        }
        
    } catch (error) {
        console.error('Meeldetuletuse salvestamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

// ==========================================
// MODALI FUNKTSIOONID
// ==========================================

function openReminderModal() {
    const modal = safeGetElement('reminderModal');
    if (modal) {
        modal.style.display = 'flex';
        const messageField = safeGetElement('reminder-message');
        if (messageField) messageField.focus();
    }
}

function closeReminderModal() {
    const modal = safeGetElement('reminderModal');
    if (modal) {
        modal.style.display = 'none';
    }
    resetReminderForm();
    isEditingReminder = false;
}

function resetReminderForm() {
    const form = safeGetElement('reminder-form');
    if (form) {
        form.reset();
        const reminderIdField = safeGetElement('reminder-id');
        const deleteBtn = safeGetElement('delete-reminder-btn');
        const recurringSettings = safeGetElement('recurring-settings');
        const tempFlag = safeGetElement('reminder-is-temporary');
        
        if (reminderIdField) reminderIdField.value = '';
        if (deleteBtn) deleteBtn.style.display = 'none';
        if (recurringSettings) recurringSettings.style.display = 'none';
        if (tempFlag) tempFlag.remove();
    }
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ==========================================
// SÜNDMUSE MODALI INTEGRATSIOON
// ==========================================

function openEventModalWithReminders(eventData = null) {
    if (window.originalOpenEventModal) {
        window.originalOpenEventModal(eventData);
    } else {
        originalOpenEventModalLogic(eventData);
    }
    
    if (eventData && eventData.id) {
        setTimeout(() => {
            loadEventReminders(eventData.id);
        }, 100);
    } else {
        currentEventReminders = [];
        renderReminders();
    }
}

function originalOpenEventModalLogic(eventData) {
    const modal = document.getElementById('eventModal');
    const title = document.getElementById('modal-title');
    const deleteBtn = document.getElementById('delete-btn');
    
    if (!modal || !title) {
        console.error('Modal elemendid ei leitud');
        return;
    }
    
    if (eventData) {
        title.textContent = 'Muuda sündmust';
        if (deleteBtn) deleteBtn.style.display = 'inline-flex';
        
        const fields = {
            'event-id': eventData.id || '',
            'event-title': eventData.title || '',
            'event-description': eventData.description || '',
            'event-location': eventData.location || '',
            'event-category': eventData.category_id || ''
        };
        
        Object.entries(fields).forEach(([id, value]) => {
            const field = document.getElementById(id);
            if (field) field.value = value;
        });
        
        if (eventData.start_datetime) {
            const startDate = new Date(eventData.start_datetime);
            const startField = document.getElementById('event-start');
            if (startField) startField.value = formatDateForInput(startDate);
        }
        
        if (eventData.end_datetime) {
            const endDate = new Date(eventData.end_datetime);
            const endField = document.getElementById('event-end');
            if (endField) endField.value = formatDateForInput(endDate);
        }
    } else {
        title.textContent = 'Lisa uus sündmus';
        const form = document.getElementById('event-form');
        if (form) form.reset();
        if (deleteBtn) deleteBtn.style.display = 'none';
    }
    
    modal.style.display = 'flex';
}

function formatDateForInput(date) {
    if (!date || isNaN(date.getTime())) return '';
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// ==========================================
// FUNKTSIOONIDE ASENDAMINE
// ==========================================

if (typeof window.originalOpenEventModal === 'undefined' && typeof window.openEventModal === 'function') {
    window.originalOpenEventModal = window.openEventModal;
}

window.openEventModal = openEventModalWithReminders;

// ==========================================
// CSS TÄIENDUSED AJUTISTE JAOKS
// ==========================================

const style = document.createElement('style');
style.textContent = `
    .reminder-item.temporary {
        border: 2px dashed var(--warning-color);
        background: rgba(245, 158, 11, 0.05);
    }
    
    .reminder-item.temporary .reminder-text {
        color: var(--gray-700);
    }
`;
document.head.appendChild(style);

// ==========================================
// EVENT LISTENERS
// ==========================================

document.addEventListener('DOMContentLoaded', function() {
    const recurringCheckbox = safeGetElement('reminder-recurring');
    if (recurringCheckbox) {
        recurringCheckbox.addEventListener('change', function() {
            const settings = safeGetElement('recurring-settings');
            if (settings) {
                settings.style.display = this.checked ? 'block' : 'none';
            }
        });
    }
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const reminderModal = safeGetElement('reminderModal');
            if (reminderModal && reminderModal.style.display === 'flex') {
                closeReminderModal();
            }
        }
    });
    
    const reminderModal = safeGetElement('reminderModal');
    if (reminderModal) {
        reminderModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeReminderModal();
            }
        });
    }
});

// Ekspordi meeldetuletuste funktsioonid globaalselt
window.addReminder = addReminder;
window.editReminder = editReminder;
window.editTemporaryReminder = editTemporaryReminder;
window.deleteReminder = deleteReminder;
window.deleteTemporaryReminder = deleteTemporaryReminder;
window.openReminderModal = openReminderModal;
window.closeReminderModal = closeReminderModal;
window.saveReminder = saveReminder;
window.loadEventReminders = loadEventReminders;
window.saveTemporaryReminders = saveTemporaryReminders;

debugLog('Meeldetuletuste süsteem laaditud (wizard integratsiooniga ja detailse infoga)!');