import { useEffect, useState } from 'react';

import { LossByDefect, getLossByDefect } from '@/app/lib/data/dashboard';
import { defectToLabel } from '@/app/lib/defect.enum';

import { BarChart } from './BarChart/BarChart';

export function LossByDefectChart() {
    const [lossByDefect, setLossByDefect] = useState<LossByDefect>([]);

    useEffect(() => {
        async function fetchData() {
            const lossByDefect = await getLossByDefect();
            setLossByDefect(lossByDefect);
        }
        fetchData();
    }, []);

    return (
        <BarChart 
            data={{
                labels: lossByDefect.map(({ _id }) => defectToLabel(_id)),
                datasets: [{ data: lossByDefect.map(({ weight }) => weight) }],
            }}
            opts={{ 
                indexAxis: 'y',
                plugins: { 
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: (context) => `${context.formattedValue} lbs`,
                        },
                    },
                },
                responsive: true,
                scales: {
                    x: {
                        ticks: {
                            callback: (value: string | number) => `${value} lbs`,
                        },
                    },
                },
            }}
            title='Loss by Defect'
        />
    );
}