{% extends 'base.html' %}
{% load static %}

{% block title %}Notification Preferences{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-900">Notification Preferences</h1>
        <button id="savePreferences" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
            <span>💾</span>Save Preferences
        </button>
    </div>

    <!-- Notification Preferences Form -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="mb-6">
            <h2 class="text-lg font-semibold text-gray-900 mb-2">Notification Channels</h2>
            <p class="text-gray-600">Choose how you want to receive different types of notifications.</p>
        </div>

        <form id="preferencesForm">
            <div class="space-y-6">
                {% for notification_type in notification_types %}
                <div class="border border-gray-200 rounded-lg p-4">
                    <h3 class="text-md font-medium text-gray-900 mb-3">
                        {{ notification_type|title|replace:"_":" " }}
                    </h3>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        {% for channel in channels %}
                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="checkbox" 
                                       name="{{ notification_type }}_{{ channel }}_enabled"
                                       class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                       {% if preferences|get_item:notification_type|get_item:channel.enabled %}checked{% endif %}>
                                <span class="ml-2 text-sm font-medium text-gray-700">
                                    <i class="fas fa-{% if channel == 'in_app' %}bell{% elif channel == 'email' %}envelope{% elif channel == 'sms' %}sms{% else %}mobile-alt{% endif %} mr-1"></i>
                                    {{ channel|title|replace:"_":" " }}
                                </span>
                            </label>
                            
                            <select name="{{ notification_type }}_{{ channel }}_frequency" 
                                    class="block w-full text-sm border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                {% for freq_value, freq_label in frequency_choices %}
                                <option value="{{ freq_value }}" 
                                        {% if preferences|get_item:notification_type|get_item:channel.frequency == freq_value %}selected{% endif %}>
                                    {{ freq_label }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                {% endfor %}
            </div>
        </form>

        <!-- Quiet Hours Settings -->
        <div class="mt-8 border-t pt-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">Quiet Hours</h3>
            <p class="text-gray-600 mb-4">Set times when you don't want to receive notifications (except urgent ones).</p>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Start Time</label>
                    <input type="time" id="quietHoursStart" 
                           class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">End Time</label>
                    <input type="time" id="quietHoursEnd" 
                           class="block w-full border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                </div>
            </div>
        </div>

        <!-- Quick Presets -->
        <div class="mt-8 border-t pt-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">Quick Presets</h3>
            <div class="flex flex-wrap gap-2">
                <button type="button" class="preset-btn bg-green-100 hover:bg-green-200 text-green-800 px-3 py-1 rounded-full text-sm" 
                        data-preset="all">
                    Enable All
                </button>
                <button type="button" class="preset-btn bg-yellow-100 hover:bg-yellow-200 text-yellow-800 px-3 py-1 rounded-full text-sm" 
                        data-preset="essential">
                    Essential Only
                </button>
                <button type="button" class="preset-btn bg-blue-100 hover:bg-blue-200 text-blue-800 px-3 py-1 rounded-full text-sm" 
                        data-preset="in_app_only">
                    In-App Only
                </button>
                <button type="button" class="preset-btn bg-red-100 hover:bg-red-200 text-red-800 px-3 py-1 rounded-full text-sm" 
                        data-preset="minimal">
                    Minimal
                </button>
            </div>
        </div>
    </div>

    <!-- Notification Statistics -->
    <div class="mt-8 bg-white rounded-lg shadow-md p-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">Your Notification Statistics</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-blue-50 rounded-lg p-4">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <span>🔔</span>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-blue-900">Total Notifications</p>
                        <p class="text-2xl font-bold text-blue-600" id="totalNotifications">-</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-green-50 rounded-lg p-4">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <span>✓</span>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-green-900">Read Rate</p>
                        <p class="text-2xl font-bold text-green-600" id="readRate">-</p>
                    </div>
                </div>
            </div>
            
            <div class="bg-yellow-50 rounded-lg p-4">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <span>⏰</span>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-yellow-900">Unread</p>
                        <p class="text-2xl font-bold text-yellow-600" id="unreadCount">-</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Success/Error Messages -->
<div id="messageContainer" class="fixed top-4 right-4 z-50"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const saveBtn = document.getElementById('savePreferences');
    const form = document.getElementById('preferencesForm');
    const presetBtns = document.querySelectorAll('.preset-btn');
    
    // Load notification statistics
    loadNotificationStats();
    
    // Save preferences
    saveBtn.addEventListener('click', function() {
        const formData = new FormData(form);
        const preferences = {};
        
        // Parse form data into preferences structure
        for (let [key, value] of formData.entries()) {
            const parts = key.split('_');
            if (parts.length >= 3) {
                const notificationType = parts.slice(0, -2).join('_');
                const channel = parts[parts.length - 2];
                const setting = parts[parts.length - 1];
                
                if (!preferences[notificationType]) {
                    preferences[notificationType] = {};
                }
                if (!preferences[notificationType][channel]) {
                    preferences[notificationType][channel] = {};
                }
                
                if (setting === 'enabled') {
                    preferences[notificationType][channel].enabled = true;
                } else if (setting === 'frequency') {
                    preferences[notificationType][channel].frequency = value;
                }
            }
        }
        
        // Add quiet hours
        const quietStart = document.getElementById('quietHoursStart').value;
        const quietEnd = document.getElementById('quietHoursEnd').value;
        
        if (quietStart && quietEnd) {
            for (let notificationType in preferences) {
                for (let channel in preferences[notificationType]) {
                    preferences[notificationType][channel].quiet_hours_start = quietStart;
                    preferences[notificationType][channel].quiet_hours_end = quietEnd;
                }
            }
        }
        
        // Save preferences
        fetch('{% url "utils:notification_preferences" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(preferences)
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showMessage('Preferences saved successfully!', 'success');
            } else {
                showMessage('Error saving preferences: ' + data.message, 'error');
            }
        })
        .catch(error => {
            showMessage('Error saving preferences: ' + error.message, 'error');
        });
    });
    
    // Preset buttons
    presetBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const preset = this.dataset.preset;
            applyPreset(preset);
        });
    });
    
    function applyPreset(preset) {
        const checkboxes = form.querySelectorAll('input[type="checkbox"]');
        const selects = form.querySelectorAll('select');
        
        checkboxes.forEach(checkbox => {
            const name = checkbox.name;
            
            switch (preset) {
                case 'all':
                    checkbox.checked = true;
                    break;
                case 'essential':
                    checkbox.checked = name.includes('loan_approved') || 
                                     name.includes('loan_rejected') || 
                                     name.includes('payment_due') || 
                                     name.includes('security_alert');
                    break;
                case 'in_app_only':
                    checkbox.checked = name.includes('in_app');
                    break;
                case 'minimal':
                    checkbox.checked = name.includes('security_alert') && name.includes('in_app');
                    break;
            }
        });
        
        selects.forEach(select => {
            if (preset === 'minimal') {
                select.value = 'daily';
            } else {
                select.value = 'immediate';
            }
        });
        
        showMessage(`Applied ${preset} preset`, 'info');
    }
    
    function loadNotificationStats() {
        fetch('{% url "utils:get_notification_stats" %}')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                document.getElementById('totalNotifications').textContent = data.stats.total_notifications;
                document.getElementById('readRate').textContent = data.stats.read_rate.toFixed(1) + '%';
                document.getElementById('unreadCount').textContent = data.stats.unread_notifications;
            }
        })
        .catch(error => {
            console.error('Error loading stats:', error);
        });
    }
    
    function showMessage(message, type) {
        const container = document.getElementById('messageContainer');
        const messageDiv = document.createElement('div');
        
        const bgColor = type === 'success' ? 'bg-green-500' : 
                       type === 'error' ? 'bg-red-500' : 'bg-blue-500';
        
        messageDiv.className = `${bgColor} text-white px-4 py-2 rounded-lg shadow-lg mb-2 transition-opacity duration-300`;
        messageDiv.textContent = message;
        
        container.appendChild(messageDiv);
        
        setTimeout(() => {
            messageDiv.style.opacity = '0';
            setTimeout(() => {
                container.removeChild(messageDiv);
            }, 300);
        }, 3000);
    }
});
</script>
{% endblock %}