import { useEffect, useState } from 'react';

import { CategorizedOperatorLoss, getLossCategoriesByOperator } from '@/app/lib/data/dashboard';

import { BarChart } from './BarChart/BarChart';
import { binToLabel } from '@/app/lib/bin.enum';
import { ChartDataset } from 'chart.js';

const dataToDataset = (data: CategorizedOperatorLoss) => {
    const labels = [];
    const datasets: ChartDataset<"bar">[]  = [];
    const bgColors = ['red', 'orange', 'blue', 'green'];
    for (const [operator, binWeights] of Object.entries(data)) {
        labels.push(operator);
        Object.entries(binWeights).forEach(([bin, weight]) => {
            datasets[parseInt(bin)] = {
                label: datasets[parseInt(bin)]?.label || binToLabel(parseInt(bin)),
                data: [...datasets[parseInt(bin)]?.data || [], weight],
                backgroundColor: datasets[parseInt(bin)]?.backgroundColor || bgColors[parseInt(bin)],
                stack: 'bar',
            };
        });
    }
    return { labels, datasets };
};

export function CategorizedLossByOperatorChart() {
    const [operatorLoss, setOperatorLoss] = useState<CategorizedOperatorLoss>({});

    useEffect(() => {
        async function fetchData() {
            const operatorLoss = await getLossCategoriesByOperator();
            setOperatorLoss(operatorLoss);
        }
        fetchData();
    }, []);

    return (
        <BarChart 
            data={dataToDataset(operatorLoss)}
            opts={{
                indexAxis: 'y',
                plugins: { 
                    legend: { display: true },
                    tooltip: {
                        callbacks: {
                            label: (context) => `${context.formattedValue} lbs`,
                        },
                    },
                },
                responsive: true,
                scales: {
                    x: {
                        stacked: true,
                        ticks: {
                            callback: (value: string | number) => `${value} lbs`,
                        },
                    },
                    y: { 
                        stacked: true,
                    }
                },
            }}
            title='Categorized Loss by Operator'
        />
    );
}