// js/main.js - Dashboard Version with Enhanced Features
const API_BASE_URL = '/est-concours/model/api/admin.php';

// Dashboard specific variables
let statsChart = null;
let demandesChart = null;
let avancementsChart = null;
let refreshInterval = null;
const AUTO_REFRESH_DELAY = 60000; // 60 seconds

// Initialize dashboard on page load
document.addEventListener('DOMContentLoaded', function () {
    loadDashboardStats();
    loadCharts();
    loadRecentActivity();

    // Set up auto-refresh
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    refreshInterval = setInterval(() => {
        refreshDashboard();
    }, AUTO_REFRESH_DELAY);
});

/**
 * Refresh dashboard manually
 */
function refreshDashboard() {
    const btn = document.querySelector('.header-actions .btn-primary');
    if (btn) {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Chargement...';
        btn.disabled = true;
    }

    loadDashboardStats();
    loadCharts();
    loadRecentActivity();

    setTimeout(() => {
        if (btn) {
            btn.innerHTML = '<i class="fas fa-sync-alt me-1"></i> Rafraîchir';
            btn.disabled = false;
        }
    }, 1500);
}

/**
 * Load dashboard statistics
 */
function loadDashboardStats() {
    const container = document.getElementById('stats-container');

    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderStats(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
                container.innerHTML = `<div class="stat-card" style="grid-column: 1 / -1; text-align: center; border-left-color: var(--danger-color);">
                    <div style="color: var(--danger-color);">
                        <i class="fas fa-exclamation-circle" style="font-size: 2rem;"></i>
                        <p style="margin-top: 10px;">Erreur de chargement des statistiques</p>
                    </div>
                </div>`;
            }
        })
        .catch(error => {
            showToast('Erreur de connexion au serveur', 'error');
            container.innerHTML = `<div class="stat-card" style="grid-column: 1 / -1; text-align: center; border-left-color: var(--danger-color);">
                <div style="color: var(--danger-color);">
                    <i class="fas fa-exclamation-circle" style="font-size: 2rem;"></i>
                    <p style="margin-top: 10px;">Erreur de connexion au serveur</p>
                </div>
            </div>`;
            console.error('Error:', error);
        });
}

/**
 * Render statistics cards - 4 per row
 */
function renderStats(stats) {
    const container = document.getElementById('stats-container');

    // Define card configurations with trends matching your image
    const cards = [
        {
            icon: 'fa-users',
            number: stats.students || 40,
            label: 'Étudiants',
            color: 'primary',
            trend: '+12%',
            trendDirection: 'up'
        },
        {
            icon: 'fa-trophy',
            number: stats.concours || 3,
            label: 'Concours',
            color: 'green',
            trend: '+3',
            trendDirection: 'up'
        },
        {
            icon: 'fa-file-alt',
            number: stats.demandes || 2,
            label: 'Demandes',
            color: 'orange',
            trend: '-5%',
            trendDirection: 'down'
        },
        {
            icon: 'fa-user-plus',
            number: stats.inscriptions || 70,
            label: 'Inscriptions',
            color: 'purple',
            trend: '+8%',
            trendDirection: 'up'
        },
        {
            icon: 'fa-arrow-up',
            number: stats.avancements || 3,
            label: 'Avancements',
            color: 'teal',
            trend: '+15%',
            trendDirection: 'up'
        },
        {
            icon: 'fa-clock',
            number: stats.pendingAvancements || 1,
            label: 'En attente',
            color: 'red',
            trend: '0',
            trendDirection: 'neutral'
        },
        {
            icon: 'fa-chalkboard-teacher',
            number: stats.professeurs || 4,
            label: 'Professeurs',
            color: 'blue',
            trend: '+2',
            trendDirection: 'up'
        },
        {
            icon: 'fa-calendar-week',
            number: stats.recentInscriptions || 2,
            label: '7 derniers jours',
            color: 'indigo',
            trend: '+25%',
            trendDirection: 'up'
        }
    ];

    container.innerHTML = cards.map((card, index) => `
        <div class="stat-card ${card.color}" style="animation-delay: ${(index * 0.05) + 0.05}s;">
            <div class="stat-content">
                <div class="stat-info">
                    <div class="stat-number">${formatNumber(card.number)}</div>
                    <div class="stat-label">${card.label}</div>
                    <div class="stat-trend ${card.trendDirection}">
                        <i class="fas ${card.trendDirection === 'up' ? 'fa-arrow-up' : card.trendDirection === 'down' ? 'fa-arrow-down' : 'fa-minus'}"></i>
                        ${card.trend}
                    </div>
                </div>
                <div class="stat-icon-wrapper ${card.color}">
                    <i class="fas ${card.icon}"></i>
                </div>
            </div>
        </div>
    `).join('');
}

/**
 * Format number (add K, M suffixes if needed)
 */
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    }
    if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num;
}

/**
 * Load charts
 */
function loadCharts() {
    loadInscriptionsChart();
    loadDemandesChart();
    loadAvancementsChart();
}

/**
 * Load inscriptions chart (Pie chart)
 */
function loadInscriptionsChart() {
    fetch(`${API_BASE_URL}?action=inscriptions`)
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data) {
                createInscriptionsChart(result.data);
            } else {
                console.error('Error loading inscriptions data:', result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Erreur de chargement des données d\'inscriptions', 'error');
        });
}

/**
 * Create inscriptions pie chart with enhanced styling
 */
function createInscriptionsChart(data) {
    const ctx = document.getElementById('concoursChart').getContext('2d');

    // Enhanced color palette
    const colors = [
        '#1a5276', '#2e86c1', '#27ae60', '#f39c12', '#8e44ad',
        '#1abc9c', '#e74c3c', '#3498db', '#e67e22', '#2c3e50'
    ];

    const labels = data.labels || [];
    const values = data.values || [];

    if (labels.length === 0) {
        showEmptyChart(ctx, 'Aucune donnée disponible');
        return;
    }

    if (statsChart) {
        statsChart.destroy();
    }

    statsChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: values,
                backgroundColor: colors.slice(0, labels.length),
                borderWidth: 3,
                borderColor: '#fff',
                hoverOffset: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '65%',
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        font: {
                            size: 11,
                            weight: '500'
                        },
                        padding: 12,
                        boxWidth: 12,
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(26, 42, 58, 0.9)',
                    titleFont: {
                        size: 13,
                        weight: '600'
                    },
                    bodyFont: {
                        size: 12
                    },
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = total > 0 ? ((context.parsed / total) * 100).toFixed(1) : 0;
                            return `${context.label}: ${context.parsed} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

/**
 * Load demandes chart (Bar chart)
 */
function loadDemandesChart() {
    fetch(`${API_BASE_URL}?action=demandes`)
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data) {
                createDemandesChart(result.data);
            } else {
                console.error('Error loading demandes data:', result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Erreur de chargement des données des demandes', 'error');
        });
}

/**
 * Create demandes bar chart with enhanced styling
 */
function createDemandesChart(data) {
    const ctx = document.getElementById('demandesChart').getContext('2d');

    const labels = data.labels || [];
    const values = data.values || [];

    if (labels.length === 0) {
        showEmptyChart(ctx, 'Aucune donnée disponible');
        return;
    }

    if (demandesChart) {
        demandesChart.destroy();
    }

    // Create gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, 'rgba(26, 82, 118, 0.9)');
    gradient.addColorStop(1, 'rgba(46, 134, 193, 0.5)');

    demandesChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Demandes de documents',
                data: values,
                backgroundColor: gradient,
                borderColor: '#1a5276',
                borderWidth: 2,
                borderRadius: 6,
                hoverBackgroundColor: '#2e86c1'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(26, 42, 58, 0.9)',
                    titleFont: {
                        size: 13,
                        weight: '600'
                    },
                    bodyFont: {
                        size: 12
                    },
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            return `Demandes: ${context.parsed.y}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        font: {
                            size: 11
                        }
                    },
                    grid: {
                        color: 'rgba(0,0,0,0.06)',
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        font: {
                            size: 10
                        },
                        maxRotation: 45,
                        minRotation: 30
                    }
                }
            }
        }
    });
}

/**
 * Load avancements chart
 */
function loadAvancementsChart() {
    fetch(`${API_BASE_URL}?action=avancements`)
        .then(response => response.json())
        .then(result => {
            if (result.success && result.data) {
                createAvancementsChart(result.data);
            } else {
                console.error('Error loading avancements data:', result.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Erreur de chargement des données des avancements', 'error');
        });
}

/**
 * Create avancements bar chart with enhanced styling
 */
function createAvancementsChart(data) {
    const ctx = document.getElementById('avancementsChart').getContext('2d');

    const labels = data.labels || [];
    const values = data.values || [];

    if (labels.length === 0) {
        showEmptyChart(ctx, 'Aucune donnée disponible');
        return;
    }

    if (avancementsChart) {
        avancementsChart.destroy();
    }

    // Create gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, 'rgba(39, 174, 96, 0.9)');
    gradient.addColorStop(1, 'rgba(46, 204, 113, 0.4)');

    avancementsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Avancements',
                data: values,
                backgroundColor: gradient,
                borderColor: '#27ae60',
                borderWidth: 2,
                borderRadius: 6,
                hoverBackgroundColor: '#2ecc71'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(26, 42, 58, 0.9)',
                    titleFont: {
                        size: 13,
                        weight: '600'
                    },
                    bodyFont: {
                        size: 12
                    },
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            return `Avancements: ${context.parsed.y}`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        font: {
                            size: 11
                        }
                    },
                    grid: {
                        color: 'rgba(0,0,0,0.06)',
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        font: {
                            size: 10
                        },
                        maxRotation: 45,
                        minRotation: 30
                    }
                }
            }
        }
    });
}

/**
 * Load recent activity
 */
function loadRecentActivity() {
    // This would typically fetch from an API
    // For now, we'll keep the static content
}

/**
 * Show empty chart message
 */
function showEmptyChart(ctx, message) {
    const canvas = ctx.canvas;
    const parent = canvas.parentElement;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    parent.innerHTML = `
        <div class="chart-empty">
            <i class="fas fa-chart-simple"></i>
            <p>${message}</p>
        </div>
    `;
}

/**
 * Show toast notification
 */
function showToast(message, type = 'info') {
    let container = document.getElementById('toastContainer');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toastContainer';
        container.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-width: 400px;
            width: 100%;
        `;
        document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    const colors = {
        success: '#27ae60',
        error: '#e74c3c',
        warning: '#f39c12',
        info: '#1a5276'
    };

    toast.style.cssText = `
        padding: 14px 20px;
        border-radius: 10px;
        color: white;
        font-weight: 500;
        font-size: 14px;
        box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        animation: slideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        background: ${colors[type] || colors.info};
        display: flex;
        align-items: center;
        gap: 12px;
        border-left: 4px solid rgba(255,255,255,0.3);
        transition: all 0.3s ease;
        cursor: default;
    `;

    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };

    toast.innerHTML = `
        <span style="font-size: 20px;">${icons[type] || 'ℹ️'}</span>
        <span style="flex: 1;">${message}</span>
        <button onclick="this.parentElement.remove()" style="
            background: none;
            border: none;
            color: rgba(255,255,255,0.7);
            cursor: pointer;
            font-size: 18px;
            padding: 0 4px;
            transition: color 0.2s;
        ">&times;</button>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(30px)';
            setTimeout(() => {
                toast.remove();
            }, 300);
        }
    }, 4000);
}

// Add animation style
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateX(100%);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
`;
document.head.appendChild(style);

// Export functions for debugging and manual refresh
window.refreshDashboard = refreshDashboard;
window.loadDashboardStats = loadDashboardStats;
window.loadCharts = loadCharts;
