
// USER DEFINED FUNCTION TO MAKE GRADIENT COLORS FOR THE CHARTS
function gradientMaker(count, startColor, endColor) {
    const colors = [];
    if (count == 1) {
        return 'rgb(229, 84, 81)';
    }
    for (let i = 0; i < count; i++) {
        const r = Math.round(startColor[0] + (endColor[0] - startColor[0]) * (i / (count - 1)));
        const g = Math.round(startColor[1] + (endColor[1] - startColor[1]) * (i / (count - 1)));
        const b = Math.round(startColor[2] + (endColor[2] - startColor[2]) * (i / (count - 1)));
        colors.push(`rgb(${r}, ${g}, ${b})`);
    }

    return colors;
}

const noDataPlugin = {
    id: 'noData',
    afterDraw(chart) {
        const datasets = chart.data.datasets;
        const hasData = datasets.some(ds => ds.data.some(item => item !== 0));

        if (!hasData) {
            const { ctx, chartArea: { left, right, top, bottom } } = chart;
            const centerX = (left + right) / 2;
            const centerY = (top + bottom) / 2;

            ctx.save();
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.font = '16px sans-serif';
            ctx.fillStyle = '#666';
            ctx.fillText('No data to display', centerX, centerY);
            ctx.restore();
        }
    }
};
Chart.register(noDataPlugin, ChartDataLabels);


function removeCharts(chartRegistry, id) {
    if (chartRegistry[id]) {
        chartRegistry[id].destroy();
        delete chartRegistry[id];
    }
}

// FUNCTION TO CALL THE CHART AS PER ID
function initChart(id) {
    function formatIndianNumber(value) {
        let num = Number(value);
        if (isNaN(num)) {
            return value;
        }

        if (num >= 10000000) {
            return (num / 10000000).toFixed(2) + " Cr";
        } else if (num >= 100000) {
            return (num / 100000).toFixed(2) + " L";
        } else if (num >= 1000) {
            return (num / 1000).toFixed(2) + "K";
        } else {
            return num.toLocaleString("en-IN");
        }
    }

    const ctx = document.getElementById(id);
    let config = null;
    if (!ctx) return;
    removeCharts(chartRegistry, id);

    const baseId = id.replace('_modal', '');
    const dlFormatter = (value) => {
        if (baseId === "averageDeliveryDays") return value + " days";
        if (baseId.toLowerCase().includes("revenue")) return "₹" + formatIndianNumber(value);
        return value;
    };

    const optsDL_Y = {
        responsive: true,
        plugins: {
            legend: { display: false, labels: { color: 'white' } },
            datalabels: { display: true, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function (value) {
                        const num = Number(value);

                        if (!isNaN(num)) {
                            return formatIndianNumber(num);
                        }
                        return String(value);
                    },
                    color: "white"
                }
            },
            x: { ticks: { color: 'white' } }
        }
    };

    const removeDataLabels_Y = {
        responsive: true,
        plugins: {
            legend: { display: false, labels: { color: 'white' } },
            datalabels: { display: false, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
        },
        scales: {
            y: {
                beginAtZero: false,
                ticks: {
                    callback: function (value) {
                        const num = Number(value);

                        if (!isNaN(num)) {
                            return formatIndianNumber(num);
                        }
                        return String(value);
                    },
                    color: "white"
                }
            },
            x: { ticks: { color: 'white' } }
        }
    };


    const optsDL_X = {
        responsive: true,
        plugins: {
            legend: { display: false, labels: { color: 'white' } },
            datalabels: { display: true, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
        },
        scales: {
            x: {
                beginAtZero: true,
                ticks: {
                    callback: function (value) {
                        const num = Number(value);

                        if (!isNaN(num)) {
                            return formatIndianNumber(num);
                        }
                        return String(value);
                    },
                    color: "white"
                }
            },
            y: { ticks: { color: 'white' } }
        }
    };

    const removeDataLabels_X = {
        responsive: true,
        plugins: {
            legend: { display: false, labels: { color: 'white' } },
            datalabels: { display: false, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
        },
        scales: {
            x: {
                beginAtZero: false,
                ticks: {
                    callback: function (value) {
                        const num = Number(value);

                        if (!isNaN(num)) {
                            return formatIndianNumber(num);
                        }
                        return String(value);
                    },
                    color: "white"
                }
            },
            y: { ticks: { color: 'white' } }
        }
    };

    switch (baseId) {
        case "revenueByCategory":
            chartRegistry[id] = new Chart(ctx, {
                type: "doughnut",
                data: {
                    labels: categories,
                    datasets: [{ data: revenue_by_categories, backgroundColor: ["#00C49F", "#0088FE", "#FFBB28", "#FF8042", "#A028FF"] }]
                },
                options: { ...optsDL_Y, scales: undefined, plugins: { ...optsDL_Y.plugins, legend: { display: true, labels: { color: 'white' } } } },
                plugins: [ChartDataLabels]
            });
            break;

        case "ordersByStatus":
            chartRegistry[id] = new Chart(ctx, {
                type: "bar",
                data: {
                    labels: order_status,
                    datasets: [{ data: order_count, backgroundColor: ["#00C49F", "#FFBB28", "#FF4444", "#0088FE", "#A028FF", "#FF8042", "#4CAF50", "#E91E63", "#9C27B0", "#795548", "#00BCD4", "#607D8B"] }]
                },
                options: optsDL_Y,
                plugins: [ChartDataLabels]
            });
            break;

        case "revenueByPayment":
            chartRegistry[id] = new Chart(ctx, {
                type: "bar",
                data: {
                    labels: payment_methods,
                    datasets: [{ data: revenue_by_payment, backgroundColor: ["#00C49F", "#0088FE", "#FFBB28", "#FF4444", "#A028FF", "#FF8042", "#4CAF50", "#E91E63", "#00BCD4"] }]
                },
                options: { ...optsDL_X, indexAxis: 'y' },
                plugins: [ChartDataLabels]
            });
            break;

        case "ordersByGender":
            chartRegistry[id] = new Chart(ctx, {
                type: "doughnut",
                data: {
                    labels: genders,
                    datasets: [{ data: order_count_by_gender, backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"] }]
                },
                options: { ...optsDL_Y, scales: undefined, plugins: { ...optsDL_Y.plugins, legend: { display: true, labels: { color: 'white' } } } },
                plugins: [ChartDataLabels]
            });
            break;

        case "topCitiesRevenue":
            chartRegistry[id] = new Chart(ctx, {
                type: "bar",
                data: {
                    labels: top_cities,
                    datasets: [{ data: top_revenue, backgroundColor: ["#00C49F", "#FFBB28", "#FF4444", "#0088FE", "#A028FF", "#FF8042", "#4CAF50", "#E91E63", "#9C27B0", "#795548", "#00BCD4", "#607D8B"] }]
                },
                options: optsDL_Y,
                plugins: [ChartDataLabels]
            });
            break;

        case "averageDeliveryDays":
            chartRegistry[id] = new Chart(ctx, {
                type: "bar",
                data: {
                    labels: courier_partners,
                    datasets: [{ data: average_delivery_days, backgroundColor: ["#36A2EB", "#BA55D3", "#FF69B4", "#FF4444"] }]
                },
                options: { ...optsDL_Y, indexAxis: 'y' },
                plugins: [ChartDataLabels]
            });
            break;

        case 'revenueByYear': {
            const backgroundColors1 = gradientMaker(yearsList.length, [175, 220, 236], [0, 0, 255]);
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: yearsList, datasets: [{ label: 'Revenue', data: revenueData, backgroundColor: backgroundColors1 }] },
                options: { ...removeDataLabels_Y, scales: { ...removeDataLabels_Y.scales, y: { ...removeDataLabels_Y.scales.y, beginAtZero: false } } },
                plugins: [showDataLabels()]
            });
            break;
        }

        case 'revenueByProduct': {
            const backgroundColors2 = gradientMaker(revByProduct.length, [84, 197, 113], [4, 99, 7]);
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: product, datasets: [{ label: 'Revenue', data: revByProduct, backgroundColor: backgroundColors2 }] },
                options: { ...removeDataLabels_X, indexAxis: 'y' },
                plugins: [showDataLabels()]
            });
            break;
        }

        case 'revenueByGroup':
            chartRegistry[id] = new Chart(ctx, {
                type: 'pie',
                data: { labels: productGroups, datasets: [{ data: revenueByProductGroup, backgroundColor: ['#4bc0c0', '#ff6384', '#36a2eb'] }] },
                options: removeDataLabels_Y,
                plugins: [showPiePercentages()]
            });
            break;

        case 'revenueExpenseYOY':
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: yearsList,
                    datasets: [
                        { label: 'Revenue', data: revenueData, backgroundColor: 'green' },
                        { label: 'Expense', data: expenseData, backgroundColor: 'red' }
                    ]
                },
                options: removeDataLabels_Y,
                plugins: [showDataLabels()]
            });
            break;

        case 'revenueByQuarter': {
            let colursAvailable = ['rgba(255,99,132,0.6)', 'rgba(54,162,235,0.6)', 'rgba(255,206,86,0.6)'];
            quarterDataset = [];
            numberYears = parseInt(quarters.length/4);
            for (i=0; i<numberYears; i++){
                quarterDataset.push({
                    label: quarterYears[i],
                    data: quarterRevenue.slice(4*i,4+(4*i)),
                    backgroundColor: colursAvailable[i]
                })
            }
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Q1','Q2','Q3','Q4'],
                    datasets: quarterDataset
                },
                options: { ...removeDataLabels_Y, plugins: { ...removeDataLabels_Y.plugins, legend: { position: 'top', labels: { color: 'white' } } } },
                plugins: [showDataLabels()]
            });
            break;
        }

        case 'revenueProductYear': {
            let colorsData;
            if (yearsList.length > 2) colorsData = ['rgba(255,99,132,0.6)', 'rgba(54,162,235,0.6)', 'rgba(255,206,86,0.6)'];
            else if (yearsList.length > 1) colorsData = ['rgba(255,99,132,0.6)', 'rgba(54,162,235,0.6)'];
            else colorsData = gradientMaker(revenueByProductAndYear.length, [255, 150, 150], [255, 0, 0]);

            const customDataset2 = [];
            if (yearsList.length > 1) {
                for (let i = 0; i < yearsList.length; i++) {
                    customDataset2.push({
                        label: yearsList[i],
                        data: revenueByProductAndYear.slice(i).filter((_, idx) => idx % yearsList.length === 0),
                        backgroundColor: colorsData[i]
                    });
                }
            } else {
                customDataset2.push({ label: yearsList[0], data: revenueByProductAndYear, backgroundColor: colorsData });
            }

            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: product, datasets: customDataset2 },
                options: { ...removeDataLabels_Y, plugins: { ...removeDataLabels_Y.plugins, legend: { position: 'top', labels: { color: 'white' } } } },
                plugins: [showDataLabels()]
            });
            break;
        }

        case 'clientAcquisitionProduct': {
            const backgroundColors3 = gradientMaker(clientsAcquiredByProduct.length, [238, 232, 170], [255, 165, 0]);
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: product, datasets: [{ label: 'Clients', data: clientsAcquiredByProduct, backgroundColor: backgroundColors3 }] },
                options: removeDataLabels_Y,
                plugins: [showClientsDataLabels()]
            });
            break;
        }

        case 'clientAcquisitionYOY': {
            const backgroundColors4 = gradientMaker(clientsAcquiredByYear.length, [0, 200, 225], [0, 0, 225]);
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: yearsList, datasets: [{ label: 'Clients Acquired', data: clientsAcquiredByYear, backgroundColor: backgroundColors4 }] },
                options: { ...removeDataLabels_X, indexAxis: 'y' },
                plugins: [showClientsDataLabels()]
            });
            break;
        }

        case 'topRevenueProducts': {
            const backgroundColors5 = gradientMaker(5, [202, 34, 107], [255, 51, 170]);
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: top5product, datasets: [{ label: 'Revenue (₹)', data: top5rev, backgroundColor: backgroundColors5 }] },
                options: { ...removeDataLabels_X, indexAxis: 'y' },
                plugins: [showDataLabels()]
            });
            break;
        }

        case 'revenueExpenseProduct': {
            const customDataset = [];
            if (yearsList.length > 1) {
                for (let i = 0; i < product.length; i++) {
                    const revenues = revenueByProductAndYear.slice(i * yearsList.length, i * yearsList.length + yearsList.length);
                    const expenses = expensesByProductAndYear.slice(i * yearsList.length, i * yearsList.length + yearsList.length);
                    customDataset.push(
                        { label: product[i], data: revenues, backgroundColor: 'green' },
                        { label: '', data: expenses, backgroundColor: 'red' },
                        { label: '', data: [null, null, null], backgroundColor: 'transparent' }
                    );
                }
            } else {
                for (let i = 0; i < product.length; i++) {
                    customDataset.push(
                        { label: product[i], data: [revenueByProductAndYear[i]], backgroundColor: 'green' },
                        { label: '', data: [expensesByProductAndYear[i]], backgroundColor: 'red' },
                        { label: '', data: [null, null, null], backgroundColor: 'transparent' }
                    );
                }
            }
            chartRegistry[id] = new Chart(ctx, {
                type: 'bar',
                data: { labels: yearsList, datasets: customDataset },
                options: removeDataLabels_Y,
                plugins: [showDataLabels(), showProductLabels()]
            });
            break;
        }
        case 'prevSalesAndProfitByMarket':
            config = {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [
                        {
                            label: 'Last Year Sales (₹)',
                            data: prevsales,
                            backgroundColor: 'rgba(255, 99, 132, 1)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            yAxisID: 'y',
                            tension: 0.3
                        },
                        {
                            label: 'Current Year Sales Profit (₹)',
                            data: sales,
                            backgroundColor: 'rgba(54, 162, 235, 1)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            yAxisID: 'y1',
                            tension: 0.3
                        }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { labels: { color: 'white' } },
                        datalabels: { display: false, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
                    },
                    scales: {
                        x: { ticks: { color: 'white' } },
                        y: {
                            type: 'linear',
                            position: 'left',
                            title: { display: true, text: 'Last Sales (₹)', color: 'white' },
                            ticks: {
                                callback: function (value) {
                                    const num = Number(value);

                                    if (!isNaN(num)) {
                                        return formatIndianNumber(num);
                                    }
                                    return String(value);
                                },
                                color: "white"
                            },
                            suggestedMin: Math.min(...sales),
                            suggestedMax: Math.max(...sales) * 2
                        },
                        y1: {
                            type: 'linear',
                            position: 'right',
                            grid: { drawOnChartArea: false },
                            title: { display: true, text: 'Curretn Sales (₹)', color: 'white' },
                            ticks: {
                                callback: function (value) {
                                    const num = Number(value);

                                    if (!isNaN(num)) {
                                        return formatIndianNumber(num);
                                    }
                                    return String(value);
                                },
                                color: "white"
                            },
                            suggestedMin: Math.min(...prevsales) * 0.5,
                            suggestedMax: Math.max(...prevsales) * 1.05
                        }
                    }
                },
                plugins: [showDataLabels()]
            };
            break;
        case 'salesAndProfitByMarket':
            config = {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [
                        {
                            label: 'Last Year Profit (₹)',
                            data: prevprofit,
                            backgroundColor: 'rgba(255, 99, 132, 1)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            yAxisID: 'y',
                            tension: 0.3
                        },
                        {
                            label: 'Current Year Profit (₹)',
                            data: profit,
                            backgroundColor: 'rgba(54, 162, 235, 1)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            yAxisID: 'y1',
                            tension: 0.3
                        }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { labels: { color: 'white' } },
                        datalabels: { display: false, color: 'white', font: { weight: 'bold' }, formatter: dlFormatter }
                    },
                    scales: {
                        x: { ticks: { color: 'white' } },
                        y: {
                            type: 'linear',
                            position: 'left',
                            title: { display: true, text: 'Last Profit (₹)', color: 'white' },
                            ticks: {
                                callback: function (value) {
                                    const num = Number(value);

                                    if (!isNaN(num)) {
                                        return formatIndianNumber(num);
                                    }
                                    return String(value);
                                },
                                color: "white"
                            },
                            suggestedMin: Math.min(...profit),
                            suggestedMax: Math.max(...profit) * 2
                        },
                        y1: {
                            type: 'linear',
                            position: 'right',
                            grid: { drawOnChartArea: false },
                            title: { display: true, text: 'Current Profit (₹)', color: 'white' },
                            ticks: {
                                callback: function (value) {
                                    const num = Number(value);
                                    console.log(value, typeof value);

                                    if (!isNaN(num)) {
                                        return formatIndianNumber(num);
                                    }
                                    return String(value);
                                },
                                color: "white"
                            },
                            suggestedMin: Math.min(...prevprofit) * 0.5,
                            suggestedMax: Math.max(...prevprofit) * 1.05
                        }
                    }
                },
                plugins: [showDataLabels()]
            };
            break;
        case 'churnReasons':
            config = {
                type: 'bar',
                data: {
                    labels: churnReason,
                    datasets: [{ label: '(₹)', data: lostSales }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    plugins: {
                        legend: { display: false },
                        datalabels: { display: false }   // disable default datalabels
                    },
                    scales: {
                        x: { ticks: { color: 'white' } },
                        y: { ticks: { color: 'white' } }
                    }
                },
                plugins: [showDataLabels()]
            };
            break;

        case 'mainChart':
            config = {
                type: 'bar',
                data: {
                    labels: oppByPack,
                    datasets: [{ label: 'Purchase (₹)', data: avgByPack }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: { display: false },
                        datalabels: { display: false }   // disable default datalabels
                    },
                    scales: {
                        x: { ticks: { color: 'white' } },
                        y: { ticks: { color: 'white' } }
                    }
                },
                plugins: [showDataLabels()]
            };
            break;
    }

    if (config) {
        chartRegistry[id] = new Chart(ctx, config);
    }
}
