import { useEffect, useState } from 'react';

import { CategorizedLoss } from '@/app/lib/data/dashboard';

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

export function CategorizedLossChart({ dataGetter, title }: { dataGetter: () => Promise<CategorizedLoss>, title: string }) {
    const [categorizedLoss, setCategorizedLoss] = useState<CategorizedLoss>({});

    useEffect(() => {
        async function fetchData() {
            const categorizedLoss = await dataGetter();
            setCategorizedLoss(categorizedLoss);
        }
        fetchData();
    }, []);

    return (
        <BarChart 
            data={{
                labels: Object.keys(categorizedLoss),
                datasets: [{ data: Object.values(categorizedLoss) }],
            }}
            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={title}
        />
    );
}