import React, { FC, memo } from 'react';
import { cn }              from '../../util/bem';
import './menu-item.component.scss';

export type MenuItemPropsType = {
    id: string;
    label?: React.ReactNode;
    iconBefore?: React.ReactNode;
    iconAfter?: React.ReactNode;
    disabled?: boolean;
    selected?: boolean;
    onSelect?: (e: React.MouseEvent, id: string) => void;
    /** - `option` or `menuitem` default is `menuitem` */
    role?: string;
    weight?: 'normal' | 'bold';
}

type MenuItemAttrsType = {
    role?: string;
    'aria-disabled'?: boolean;
    'aria-selected'?: boolean;
}

const className = cn('menu-item');

export const MenuItem: FC<MenuItemPropsType> = memo((props) => {
    const handleOnSelect = (e: React.MouseEvent) => {
        if (props.onSelect) {
            props.onSelect(e, props.id);
        }
    };

    const mouseEvent = { onClick: props.disabled ? undefined : handleOnSelect };
    let attrs: MenuItemAttrsType = {
        role:            props.role,
        'aria-disabled': props.disabled
    };

    if (props.role === 'option') {
        attrs = {
            ...attrs,
            role:            'option',
            'aria-selected': props.selected
        };
    } else if (props.role === null || props.role === 'none') {
        attrs.role = 'none';
    }

    return (
        <li
            className={ className({
                disabled: props.disabled,
                selected: props.selected,
                weight:   props.weight
            }) }
            { ...attrs }
            { ...mouseEvent }
        >
            { props.children }
        </li>
    );
});

MenuItem.defaultProps = {
    role:     'menuitem',
    disabled: false,
    weight:   'normal'
};
