import React, { useEffect, useRef, useState } from 'react';

export const am5ClassName = 'armu_ai_chatbot-am5';

export function useAm5() {
    const [am5, setAm5] = useState(null);

    useEffect(() => {
        function check() {
            if (window.am5) {
                window.am5.ready(() => setAm5(window.am5));
            } else setTimeout(check, 100);
        }
        check();
    }, []);

    return am5;
}

let am5Colors = null;
export function useAm5Colors() {
    const am5 = useAm5();

    if (!am5Colors && am5) {
        am5Colors = colors.map((color) => am5.color(color));
    }

    return am5Colors;
}

const roots = {};
export function getRoot(id) {
    let root = roots[id];
    if (root) root.dispose();

    root = am5.Root.new(id);
    roots[id] = root;
    
    root.setThemes([
        am5themes_Animated.new(root)
    ]);

    root.locale = am5locales_it_IT;
    root.numberFormatter.set("numberFormat", "#,###.00");

    return root;
}

export const colors = [
    '#4CC9C3',
    '#3D9AA0',
    '#1B3353',
    '#637081',
    '#A790A5',
    '#EBE1E2',
    '#EEE8DC',
    '#D4B483'
];

export function ChartContainer(props) {
    const { id, className } = props;

    const chartRef = useRef();
    const [style, setStyle] = useState(null);
    useEffect(() => {
        if (chartRef.current) {
            setStyle({
                backgroundColor: findFirstBackgroundColor(chartRef.current),
                ...props.style
            });
        }
    }, [chartRef, props.style]);

    return (
        <div id={id} style={style} className={`${am5ClassName} ${className}`.trimEnd()} ref={chartRef} />
    )
}

ChartContainer.defaultProps = {
    id: '',
    className: '',
    style: {}
}

function findFirstBackgroundColor(element) {
    if (element) {
        const backgroundColor = getComputedStyle(element)?.backgroundColor;

        if (backgroundColor !== "rgba(0, 0, 0, 0)") {
            return backgroundColor;
        }

        if (element.parentElement) {
            return findFirstBackgroundColor(element.parentElement);
        }
    }

    return null;
}

