import Chart from 'chart.js/auto';
import { buildEndpoint } from './urlBuilder';

document.addEventListener('DOMContentLoaded', function () {
    const membershipsCanvas = document.getElementById('membershipsChart');
    const periodCanvas = document.getElementById('periodChart');

    const assistanceProgressBefore = document.getElementById('assistanceProgressBefore');
    const assistanceProgress = document.getElementById('assistanceProgress');
    const topAttendeesChartBefore  = document.getElementById('topAttendeesChartBefore');
    const topAttendeesChart  = document.getElementById('topAttendeesChart');

    const palette = [
        { bg: 'rgba(54, 162, 235, 0.35)', border: 'rgb(54, 162, 235)' },
        { bg: 'rgba(255, 159, 64, 0.35)', border: 'rgb(255, 159, 64)' },
        { bg: 'rgba(75, 192, 192, 0.35)', border: 'rgb(75, 192, 192)' },
        { bg: 'rgba(255, 99, 132, 0.35)', border: 'rgb(255, 99, 132)' },
        { bg: 'rgba(153, 102, 255, 0.35)', border: 'rgb(153, 102, 255)' },
        { bg: 'rgba(201, 203, 207, 0.35)', border: 'rgb(201, 203, 207)' },
    ];

    const renderTopAttendeesChart = (canvas, endpoint, title) => {
        if (!canvas) {
            return;
        }

        const ctx = canvas.getContext('2d');

        fetch(buildEndpoint(endpoint))
            .then((response) => response.json())
            .then((data) => {
                if (!Array.isArray(data) || data.length === 0) {
                    console.warn('No hay datos de asistentes para mostrar');
                    return;
                }

                const labels = data.map((item) => item.user_name);
                const assists = data.map((item) => item.total_assists);

                const backgroundColors = [
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)',
                    'rgba(255, 159, 64, 0.7)',
                    'rgba(199, 199, 199, 0.7)',
                    'rgba(83, 102, 255, 0.7)',
                    'rgba(255, 99, 255, 0.7)',
                    'rgba(99, 255, 132, 0.7)'
                ];

                const borderColors = [
                    'rgb(255, 99, 132)',
                    'rgb(54, 162, 235)',
                    'rgb(255, 206, 86)',
                    'rgb(75, 192, 192)',
                    'rgb(153, 102, 255)',
                    'rgb(255, 159, 64)',
                    'rgb(199, 199, 199)',
                    'rgb(83, 102, 255)',
                    'rgb(255, 99, 255)',
                    'rgb(99, 255, 132)'
                ];

                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Total de asistencias',
                            data: assists,
                            backgroundColor: backgroundColors.slice(0, data.length),
                            borderColor: borderColors.slice(0, data.length),
                            borderWidth: 2,
                            borderRadius: 8,
                            barPercentage: 0.7,
                            categoryPercentage: 0.8
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: true,
                        elements: {
                            bar: {
                                borderWidth: 2,
                            }
                        },
                        plugins: {
                            legend: {
                                position: 'top',
                                labels: {
                                    font: { size: 12 },
                                    usePointStyle: true,
                                    boxWidth: 10
                                }
                            },
                            title: {
                                display: true,
                                text: title,
                                font: { size: 16, weight: 'bold' },
                                padding: { bottom: 20 }
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        const value = context.raw;
                                        const label = context.dataset.label || '';
                                        return `${label}: ${value} asistencias`;
                                    },
                                    afterLabel: function(context) {
                                        const value = context.raw;
                                        const average = ((value / 30) * 100).toFixed(1);
                                        return `└ Promedio: ${average}% del mes`;
                                    }
                                },
                                backgroundColor: 'rgba(0,0,0,0.8)',
                                titleColor: '#fff',
                                bodyColor: '#ddd',
                                padding: 10,
                                cornerRadius: 8
                            }
                        },
                        scales: {
                            x: {
                                title: {
                                    display: true,
                                    text: 'Número de asistencias',
                                    font: { weight: 'bold', size: 12 },
                                    padding: { top: 10 }
                                },
                                grid: {
                                    display: true,
                                    drawBorder: true,
                                    color: 'rgba(0,0,0,0.05)'
                                },
                                ticks: {
                                    stepSize: 5,
                                    callback: function(value) {
                                        return value + ' días';
                                    }
                                }
                            },
                            y: {
                                title: {
                                    display: true,
                                    text: 'Usuarios',
                                    font: { weight: 'bold', size: 12 }
                                },
                                grid: {
                                    display: false,
                                    drawBorder: true
                                },
                                ticks: {
                                    font: { size: 11 },
                                    autoSkip: false
                                }
                            }
                        },
                        layout: {
                            padding: {
                                left: 10,
                                right: 10,
                                top: 10,
                                bottom: 10
                            }
                        }
                    }
                });
            })
            .catch((error) => console.error(`Error loading top attendees chart (${endpoint}):`, error));
    };

    const renderAttendanceRateChart = (canvas, endpoint) => {
        if (!canvas) {
            return;
        }

        const ctx = canvas.getContext('2d');

        fetch(buildEndpoint(endpoint))
            .then((response) => response.json())
            .then((data) => {
                const totalActive = data.total_active || 0;
                const attendedToday = data.attended_today || 0;
                const absentToday = data.absent_today || 0;
                const attendanceRate = data.attendance_rate || 0;
                const remainingRate = 100 - attendanceRate;

                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: [`Asistieron (${attendedToday})`, `Ausentes (${absentToday})`],
                        datasets: [{
                            data: [attendanceRate, remainingRate],
                            backgroundColor: ['#28a745', '#dc3545'],
                            borderWidth: 0,
                            cutout: '65%',
                            borderRadius: 5,
                            spacing: 3
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        const label = context.label || '';
                                        const value = context.raw;
                                        return `${label}: ${value.toFixed(1)}%`;
                                    }
                                }
                            },
                            legend: {
                                position: 'bottom',
                                labels: { font: { size: 11 }, usePointStyle: true, padding: 10 }
                            },
                            title: {
                                display: true,
                                text: `Asistencia del día ${data.date_formatted}`,
                                font: { size: 14, weight: 'bold' },
                                padding: { bottom: 15 }
                            }
                        }
                    }
                });

                return { totalActive, attendedToday, absentToday };
            })
            .then((attendanceData) => {
                if (!attendanceData || canvas !== assistanceProgress) {
                    return;
                }

                const attendanceBarCanvas = document.getElementById('attendanceBarChart');
                if (!attendanceBarCanvas) {
                    return;
                }

                const { totalActive, attendedToday, absentToday } = attendanceData;
                const barCtx = attendanceBarCanvas.getContext('2d');

                new Chart(barCtx, {
                    type: 'bar',
                    data: {
                        labels: ['Asistencias', 'Ausencias'],
                        datasets: [{
                            label: 'Usuarios',
                            data: [attendedToday, absentToday],
                            backgroundColor: ['#28a745', '#dc3545'],
                            borderRadius: 8,
                            barPercentage: 0.6
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        indexAxis: 'y',
                        plugins: {
                            legend: { display: false },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        const value = context.raw;
                                        const percent = totalActive > 0 ? ((value / totalActive) * 100).toFixed(1) : 0;
                                        return `${value} usuarios (${percent}%)`;
                                    }
                                }
                            },
                            title: {
                                display: true,
                                text: `Total usuarios activos: ${totalActive}`,
                                font: { size: 12 },
                                position: 'bottom'
                            }
                        },
                        scales: {
                            x: { max: totalActive, title: { display: true, text: 'Cantidad de usuarios' } },
                            y: { title: { display: true, text: 'Estado' } }
                        }
                    }
                });
            })
            .catch((error) => console.error(`Error loading attendance rate chart (${endpoint}):`, error));
    };

    if (membershipsCanvas) {
        const ctx = membershipsCanvas.getContext('2d');

        fetch(buildEndpoint('admin-fit/chart/memberschipsformoutn'))
            .then((response) => response.json())
            .then((data) => {
                const labels = data.map((item) => `${item.anio}-${String(item.mes_nombre).padStart(2, '0')}`);
                const inscripciones = data.map((item) => item.total_inscripciones);

                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels,
                        datasets: [
                            {
                                label: 'Total Inscripciones',
                                data: inscripciones,
                                backgroundColor: palette.map((color) => color.bg),
                                borderColor: palette.map((color) => color.border),
                                borderWidth: 1,
                            },
                        ],
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: 'Número de Inscripciones',
                                },
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: 'Fecha (Año-Mes)',
                                },
                            },
                        },
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top',
                            },
                            title: {
                                display: true,
                                text: 'Inscripciones por Mes',
                            },
                        },
                    },
                });
            })
            .catch((error) => console.error('Error al cargar los datos del grafico de membresias:', error));
    }

// ========== NUEVO GRÁFICO: TASA DE ASISTENCIA DEL DÍA ==========
    renderAttendanceRateChart(assistanceProgress, 'admin-fit/chart/todayattendancerate');
    renderAttendanceRateChart(assistanceProgressBefore, 'admin-fit/chart/todayattendancerate/1');

    renderTopAttendeesChart(topAttendeesChart, 'admin-fit/chart/topattendees', '🏆 Top 10 asistencias del mes');
    renderTopAttendeesChart(topAttendeesChartBefore, 'admin-fit/chart/topattendees/1', '🏆 Top 10 asistencias del mes anterior');






    if (periodCanvas) {
        const periodCtx = periodCanvas.getContext('2d');

        fetch(buildEndpoint('admin-fit/chart/daysformembership'))
            .then((response) => response.json())
            .then((payload) => {
                const labels = Array.isArray(payload.labels) ? payload.labels : [];
                const periodDatasets = Array.isArray(payload.datasets) ? payload.datasets : [];
                const totalsByDay = Array.isArray(payload.totals_by_day) ? payload.totals_by_day : [];

                const chartDatasets = periodDatasets.map((dataset, index) => {
                    const color = palette[index % palette.length];

                    return {
                        type: 'bar',
                        label: dataset.label ?? `Período ${index + 1}`,
                        data: Array.isArray(dataset.data) ? dataset.data : [],
                        backgroundColor: color.bg,
                        borderColor: color.border,
                        borderWidth: 1,
                        stack: 'periods',
                    };
                });

                if (totalsByDay.length > 0) {
                    chartDatasets.push({
                        type: 'line',
                        label: 'Total por Día',
                        data: totalsByDay,
                        borderColor: 'rgb(33, 37, 41)',
                        backgroundColor: 'rgba(33, 37, 41, 0.2)',
                        borderWidth: 2,
                        tension: 0.2,
                        fill: false,
                        yAxisID: 'y',
                    });
                }

                new Chart(periodCtx, {
                    data: {
                        labels,
                        datasets: chartDatasets,
                    },
                    options: {
                        responsive: true,
                        scales: {
                            x: {
                                stacked: true,
                                title: {
                                    display: true,
                                    text: 'Día de la semana',
                                },
                            },
                            y: {
                                beginAtZero: true,
                                stacked: true,
                                title: {
                                    display: true,
                                    text: 'Cantidad de asistencias',
                                },
                            },
                        },
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top',
                            },
                            title: {
                                display: true,
                                text: 'Asistencias por Período y Día',
                            },
                        },
                    },
                });
            })
            .catch((error) => console.error('Error al cargar los datos del grafico periodChart:', error));
    }
});