import {useEffect, useState} from "@wordpress/element";
import ButtonRounded from "../../../button/rounded";
import Tooltip from "../../../tooltip";

export default function Action({action, tooltipArrowPosition = 'center'}) {
    const [loading, setLoading] = useState(false);
    const [icon, setIcon] = useState(action.icon);
    const [buttonClassName, setButtonClassName] = useState(false);

    useEffect(() => {
        setButtonClassName((loading || action.disabled) ? 'lbaic-button-disabled' : false);
    }, [loading, action.disabled]);

    const onClick = async () => {
        if (action.disabled) {
            return;
        }
        setLoading(true);
        const result = await action.onClick();
        if (result.success) {
            setIcon(action.iconDone);
            setTimeout(() => setIcon(action.icon), 1500);
        }
        setLoading(false);
    }

    // Support custom render function for sources action
    if (action.customRender) {
        return <div className='lbaic-message-actions-in'>
            {action.customRender()}
        </div>;
    }

    return <div className='lbaic-message-actions-in'>
        {action.tooltip?.length > 0 ?
            <Tooltip tooltipPosition='top' title={action.tooltip} arrowPosition={tooltipArrowPosition}>
                <ButtonRounded className={buttonClassName} onClick={onClick} icon={icon} disabled={action.disabled}/>
            </Tooltip>
            :
            <ButtonRounded className={buttonClassName} onClick={onClick} icon={icon} disabled={action.disabled}/>}
    </div>
}