import React, { useEffect, useState } from 'react';
import { HorizontalBar } from 'react-chartjs-2';
import { Grid } from '@material-ui/core';
import { useTranslation } from 'react-i18next';

const colors = {
    loose_cargo: '#1FA0ED',
    full_truck_load: '#223A59'
};

const StackedHorizontalBarChart: React.FC<{ graphData: { loose_cargo: any[], full_truck_load: any[] } }> = ({ graphData }) => {
    const { t } = useTranslation();
    const [chartData, setChartData] = useState<any>({});

    useEffect(() => {
        const labelsSet = new Set<string>();

        // Collect all company sites to create a consistent label set
        Object.values(graphData).flat().forEach(item => labelsSet.add(item.company_site));

        const labels = Array.from(labelsSet);

        // Process each movement type (loose_cargo and full_truck_load)
        const datasets = Object.keys(graphData).map((movementType) => {
            const dataPoints = graphData[movementType].map((item: any) => ({
                company_site: item['company_site'],
                total_quantity: parseInt(item['total_quantity'], 10) || 0 // Ensure quantity is a number
            }));

            // Create dataset for each movement type
            return {
                label: t(movementType),
                backgroundColor: colors[movementType],
                borderColor: colors[movementType],
                borderWidth: 1,
                hoverBackgroundColor: colors[movementType],
                hoverBorderColor: colors[movementType],
                data: labels.map(label => {
                    const foundPoint = dataPoints.find(point => point.company_site === label);
                    return foundPoint ? foundPoint.total_quantity : 0;
                })
            };
        });

        setChartData({
            labels,
            datasets
        });
    }, [graphData, t]);

    // Options configuration
    const options = {
        responsive: true,
        // legend: {
        //     position: 'bottom',
        // },
        animation: {
            duration: 0
        },
        scales: {
            x: {
                stacked: true,
                scaleLabel: {
                    display: true,
                    labelString: t('Value')
                },
                ticks: {
                    beginAtZero: true
                }
            },
            y: {
                stacked: true,
                scaleLabel: {
                    display: true,
                    labelString: t('Company Site')
                }
            }
        }
    };

    return (
        <Grid item style={{ borderRadius: '16px', paddingTop: '20px', margin: '0 10px 10px 0', backgroundColor: 'white' }}>
            <HorizontalBar data={chartData} options={options} />
        </Grid>
    );
};

export default StackedHorizontalBarChart;
