/**
 * Charts for Reports
 * Chart.js initialization for analytics
 */

// ============================================
// Charts Manager Class
// ============================================

class ChartsManager {
    constructor() {
        this.charts = {};
        this.init();
    }
    
    init() {
        this.initCaseTrendChart();
        this.initStatusChart();
        this.initRemedyChart();
        this.initRevenueChart();
        this.initMonthlyComparisonChart();
    }
    
    initCaseTrendChart() {
        const canvas = document.getElementById('casesTrendChart');
        if (!canvas) return;
        
        const data = JSON.parse(canvas.dataset.chartData || '{}');
        
        this.charts.casesTrend = new Chart(canvas, {
            type: 'line',
            data: {
                labels: data.labels || [],
                datasets: [{
                    label: 'Cases',
                    data: data.values || [],
                    borderColor: '#2ecc71',
                    backgroundColor: 'rgba(46, 204, 113, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true,
                    pointBackgroundColor: '#2ecc71',
                    pointBorderColor: '#fff',
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'top' },
                    tooltip: { mode: 'index', intersect: false }
                },
                scales: {
                    y: { beginAtZero: true, title: { display: true, text: 'Number of Cases' } },
                    x: { title: { display: true, text: 'Month' } }
                }
            }
        });
    }
    
    initStatusChart() {
        const canvas = document.getElementById('statusChart');
        if (!canvas) return;
        
        const active = parseInt(canvas.dataset.active || 0);
        const followUp = parseInt(canvas.dataset.followUp || 0);
        const closed = parseInt(canvas.dataset.closed || 0);
        
        this.charts.status = new Chart(canvas, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Follow-up', 'Closed'],
                datasets: [{
                    data: [active, followUp, closed],
                    backgroundColor: ['#28a745', '#ffc107', '#6c757d'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'bottom' },
                    tooltip: { callbacks: { label: (ctx) => `${ctx.label}: ${ctx.raw} cases (${((ctx.raw / (active + followUp + closed)) * 100).toFixed(1)}%)` } }
                }
            }
        });
    }
    
    initRemedyChart() {
        const canvas = document.getElementById('remedyChart');
        if (!canvas) return;
        
        const remedies = JSON.parse(canvas.dataset.remedies || '[]');
        
        this.charts.remedy = new Chart(canvas, {
            type: 'bar',
            data: {
                labels: remedies.map(r => r.name),
                datasets: [{
                    label: 'Prescriptions',
                    data: remedies.map(r => r.count),
                    backgroundColor: '#3498db',
                    borderRadius: 5,
                    barPercentage: 0.7
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                indexAxis: 'y',
                plugins: {
                    legend: { position: 'top' },
                    tooltip: { callbacks: { label: (ctx) => `${ctx.raw} prescriptions` } }
                },
                scales: {
                    x: { title: { display: true, text: 'Number of Prescriptions' } }
                }
            }
        });
    }
    
    initRevenueChart() {
        const canvas = document.getElementById('revenueChart');
        if (!canvas) return;
        
        const months = JSON.parse(canvas.dataset.months || '[]');
        const revenues = JSON.parse(canvas.dataset.revenues || '[]');
        
        this.charts.revenue = new Chart(canvas, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [{
                    label: 'Revenue ($)',
                    data: revenues,
                    backgroundColor: '#28a745',
                    borderRadius: 5,
                    barPercentage: 0.7
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    tooltip: { callbacks: { label: (ctx) => `$${ctx.raw.toFixed(2)}` } }
                },
                scales: {
                    y: { title: { display: true, text: 'Revenue (USD)' }, beginAtZero: true },
                    x: { title: { display: true, text: 'Month' } }
                }
            }
        });
    }
    
    initMonthlyComparisonChart() {
        const canvas = document.getElementById('comparisonChart');
        if (!canvas) return;
        
        const currentYear = JSON.parse(canvas.dataset.currentYear || '[]');
        const previousYear = JSON.parse(canvas.dataset.previousYear || '[]');
        const labels = JSON.parse(canvas.dataset.labels || '["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]');
        
        this.charts.comparison = new Chart(canvas, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: canvas.dataset.currentYearLabel || 'Current Year',
                        data: currentYear,
                        borderColor: '#2ecc71',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        tension: 0.3,
                        fill: false
                    },
                    {
                        label: canvas.dataset.previousYearLabel || 'Previous Year',
                        data: previousYear,
                        borderColor: '#3498db',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        borderDash: [5, 5],
                        tension: 0.3,
                        fill: false
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    tooltip: { mode: 'index', intersect: false },
                    legend: { position: 'top' }
                },
                scales: {
                    y: { beginAtZero: true, title: { display: true, text: 'Number of Cases' } },
                    x: { title: { display: true, text: 'Month' } }
                }
            }
        });
    }
    
    updateChart(chartName, newData) {
        if (this.charts[chartName]) {
            if (newData.labels) this.charts[chartName].data.labels = newData.labels;
            if (newData.datasets) {
                this.charts[chartName].data.datasets.forEach((dataset, i) => {
                    if (newData.datasets[i]) dataset.data = newData.datasets[i].data;
                });
            }
            this.charts[chartName].update();
        }
    }
    
    destroyChart(chartName) {
        if (this.charts[chartName]) {
            this.charts[chartName].destroy();
            delete this.charts[chartName];
        }
    }
}

// Initialize Charts Manager
let chartsManager = null;

document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelector('[data-chart]')) {
        chartsManager = new ChartsManager();
        window.chartsManager = chartsManager;
    }
});