import type { FC } from 'react';
import { useHistory } from 'react-router-dom';

import { Menu } from '@servicetitan/anvil2';
import ExpandMoreIcon from '@servicetitan/anvil2/assets/icons/material/round/expand_more.svg';

import { SingleActionButtonSection } from './single-action-button';
import { BrandAction } from '../../../utils/interfaces';

export const ActionsButtonSection: FC<{
    actions: BrandAction | BrandAction[];
}> = ({ actions }) => {
    const history = useHistory();

    if (!Array.isArray(actions)) {
        return <SingleActionButtonSection action={actions} />;
    }

    return (
        <Menu
            label="Actions"
            className="qa-brand-card-action-menu"
            size="small"
            // @ts-expect-error Menu icon API expects a raw component, but we're passing an object with 'after' per design, Anvil has ticket to fix it
            icon={{ after: ExpandMoreIcon }}
        >
            {actions.map(action => {
                const actionClick = () => {
                    if (action.action) {
                        action.action();
                    }
                    if (action.href) {
                        history.push(action.href);
                    }
                };

                return (
                    <Menu.Item
                        disabled={action.disabled}
                        key={action.name}
                        onClick={actionClick}
                        className="qa-brand-card-action-menu-item"
                        label={action.name}
                    />
                );
            })}
        </Menu>
    );
};
