import React from 'react';
import PropTypes from 'prop-types';
import './styles/MenuItem.scss';
import Icon from '../../../../atoms/icon/Icon';
import { createNamespace } from '../../../../tools/namingTools';

const n = createNamespace('menuItem');

const MenuItemComponent = ({ menuItem, menuLevel }) => {
    if (!menuItem) {
        return null;
    }

    const hasChildren = menuItem.items && menuItem.items.length;
    const modifiers = [`level-${menuLevel}`];

    const renderSubMenuItem = (item, level) => {
        const listModifiers = [`level-${level + 1}`];

        return (
            <React.Fragment>
                <a href={item.href} {...n('link', `level-${level}`).withTestId(`link:level-${level}`).props}>
                    <span {...n('link-text', `level-${level}`).props}>{menuItem.label}</span>
                    {hasChildren && level === 0 ? <Icon type="caretDown" {...n('link-icon', `level-${level}`).props} /> : ''}
                </a>
                {hasChildren ? (
                    <ul {...n('list', listModifiers).props}>
                        {item.items.map(subMenuItem => (
                            <MenuItemComponent
                                menuItem={subMenuItem}
                                menuLevel={level + 1}
                                key={subMenuItem.label}
                            />
                        ))}
                    </ul>
                ) : ''}
            </React.Fragment>
        );
    };

    return (
        <li {...n('item', modifiers).withTestId().props}>
            {renderSubMenuItem(menuItem, menuLevel)}
        </li>
    );
};


MenuItemComponent.propTypes = {
    menuItem: PropTypes.shape({
        label: PropTypes.string,
        href: PropTypes.string,
        items: PropTypes.arrayOf(
            PropTypes.shape({
                label: PropTypes.string,
                href: PropTypes.string
            })
        )
    }),
    menuLevel: PropTypes.number
};

MenuItemComponent.defaultProps = {
    menuItem: {},
    menuLevel: 0
};

export default MenuItemComponent;
