import {
    CategoryScale,
    Chart,
    Filler,
    Legend,
    LinearScale,
    LineController,
    LineElement,
    PointElement,
    Tooltip,
} from 'chart.js';

Chart.register(
    CategoryScale,
    Filler,
    Legend,
    LinearScale,
    LineController,
    LineElement,
    PointElement,
    Tooltip,
);

const palette = ['#3b82f6', '#10b981'];

export default function trendChart({ labels = [], series = [], suffix = '', max = null } = {}) {
    return {
        chart: null,

        init() {
            this.chart = new Chart(this.$refs.canvas, {
                type: 'line',
                data: {
                    labels,
                    datasets: series.map((one, index) => ({
                        label: one.name,
                        data: one.values,
                        borderColor: palette[index % palette.length],
                        backgroundColor: palette[index % palette.length],
                        spanGaps: false,
                        tension: 0.3,
                    })),
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max,
                            ticks: {
                                precision: 0,
                                callback: (value) => `${value}${suffix}`,
                            },
                        },
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: (ctx) => `${ctx.dataset.label}: ${ctx.formattedValue}${suffix}`,
                            },
                        },
                    },
                },
            });
        },

        destroy() {
            this.chart?.destroy();
            this.chart = null;
        },
    };
}
