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

export type MenuPropsType = {
    className?: string;
    children?: ChildrenOf<typeof MenuItem> | ChildrenOf<typeof MenuItem>[];
    activeItemId?: string | null;
    onSelect?: (e: React.SyntheticEvent, id: string) => void;
    role?: string;
    style?: React.CSSProperties;
}
export type Ref = HTMLUListElement;

const className = cn('menu');

export const Menu: FC<MenuPropsType> = memo(forwardRef<Ref, MenuPropsType>((props, ref) => {
    const style = { ...props.style };

    return (
        <ul
            className={ `${ className() } ${ props.className || '' }` }
            role={ props.role }
            ref={ ref }
            style={ style }
        >
            {
                React.Children.map(props.children, (child) => (
                    React.isValidElement(child)
                        ? React.cloneElement(child, {
                            ...child.props,
                            selected: child.props.id === props.activeItemId,
                            id:       child.props.id,
                            onSelect: props.onSelect
                        })
                        : null))
            }
        </ul>
    );
}));

Menu.defaultProps = { role: 'menu' };
