import React from 'react';
import PropTypes from 'prop-types';

import Link from '../../../../../../atoms/link/Link';
import { getPropValue } from '../../../../../../tools/objectTools';
import { TARGET_BLANK } from '../../../../../../constants/buttons';
import { createNamespace } from '../../../../../../tools/namingTools';
import { getListingUrlForProductLines } from '../../../../../../tools/urlTools';

const n = createNamespace('HeaderNavigation');

const SubMenu = ({
    subMenuItems = [],
    modifiers = [],
    setItemsArrayFunction = () => {},
    locale,
    onFocus,
    onBlur,
    onMouseOver,
    onMouseLeave
}) => {
    if (!subMenuItems || !subMenuItems.length) {
        return null;
    }

    return (
        <ul
            {...n('subMenu', modifiers).withTestId('subMenu').props}
            onFocus={onFocus}
            onBlur={onBlur}
            onMouseOver={onMouseOver}
            onMouseLeave={onMouseLeave}
        >
            {subMenuItems.map(item => {
                const { isVisible, openInNewTab, uuid, editorType, customData } = item;
                const titleText = getPropValue(item, 'title.value');
                let linkUrl = getPropValue(item, 'link.value');
                const target = openInNewTab ? TARGET_BLANK : null;
                if (!isVisible || !titleText) {
                    return null;
                }
                if (editorType === 'PRODUCT_LINES') {
                    linkUrl = getListingUrlForProductLines(locale.code, customData && customData.externalUUID);
                }
                return (
                    <li
                        {...n('subMenuItem').withTestId('subMenuItem').props}
                        key={uuid}
                        ref={setItemsArrayFunction}
                    >
                        <Link {...n('subMenuLink').props} href={linkUrl || ''} target={target}>{titleText}</Link>
                    </li>
                );
            })}
        </ul>
    );
};

SubMenu.propTypes = {
    subMenuItems: PropTypes.arrayOf(PropTypes.shape()),
    modifiers: PropTypes.arrayOf(PropTypes.string),
    setItemsArrayFunction: PropTypes.func,
    locale: PropTypes.object,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onMouseOver: PropTypes.func,
    onMouseLeave: PropTypes.func
};

SubMenu.defaultProps = {
    subMenuItems: [],
    modifiers: [],
    setItemsArrayFunction: () => {},
    locale: {},
    onFocus: () => {},
    onBlur: () => {},
    onMouseOver: () => {},
    onMouseLeave: () => {}
};

export default SubMenu;
