import React from 'react';
import PropTypes from 'prop-types';
import Icon from '../../../../atoms/icon/Icon';
import { createNamespace } from '../../../../tools/namingTools';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/MenuItem.scss';

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 (
            <>
                <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>
                ) : ''}
            </>
        );
    };

    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;
