import { NumberFormatter } from 'arm-common';
import { HBox, VBox } from 'arm-core-layouts';
import p from 'prop-types';
import React, { useMemo } from 'react';

import { colors } from '../Am5.jsx';


const classNamePrefix = 'armu_ai_chatbot-pie-chart-legend';

export default function PieChartLegend(props) {
    const { data, xAxis, yAxis, enableTotal } = props;

    const total = useMemo(() => {
        if (enableTotal && data?.length) {
            return data.reduce((total, item) => total + (item[yAxis] || 0), 0);
        }
        return null;
    },[data, enableTotal]);

    if (!data || !data?.length) return null;

    return (
        <VBox className={`${classNamePrefix}`}>
            {data.map((item, index) => (
                <HBox key={`${classNamePrefix}-${item[xAxis]}-${item[yAxis]}`} className={`${classNamePrefix}-item`}>
                    <span style={{ backgroundColor: colors[index] }} className={`${classNamePrefix}-color-ref`}/>
                    
                    <span>{item[xAxis]}</span>

                    <span className={`${classNamePrefix}-value`}>{NumberFormatter.percent(item[yAxis])}</span>
                </HBox>
            ))}
            {total && (
                <>
                    <span className={`${classNamePrefix}-divisor`}/>

                    <HBox className={`${classNamePrefix}-item`}>
                        <span className={`${classNamePrefix}-color-ref`}/>

                        <span>Total</span>

                        <span className={`${classNamePrefix}-value`}>{NumberFormatter.percent(total)}</span>
                    </HBox>
                </>
            )}
        </VBox>
    );
}

PieChartLegend.defaultProps = {
    className: '',
    children: null
}

PieChartLegend.propTypes = {
    className: p.string,
    children: p.node
}