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

import { createNamespace } from '../../tools/namingTools';

import ButtonIcon from '../button-icon/ButtonIcon';
import Link from '../link/Link';
import { getPropValue } from '../../tools/objectTools';
import './styles/menuDropdown.scss';

const n = createNamespace('menuDropdown');
const getMenuDropdownItems = items => (items && items.length) && (
    <ul {...n('userDropdownList').withTestId().props}>
        {items.map(childItem => {
            const { isVisible, openInNewTab, uuid } = childItem;
            const titleText = getPropValue(childItem, 'title.value');
            const linkUrl = getPropValue(childItem, 'link.value');

            if (!isVisible || !titleText) {
                return null;
            }
            const target = openInNewTab ? '_blank' : null;
            return (
                <li {...n('userDropdownItem').props} key={uuid}>
                    <Link {...n('userDropdownLink').props} href={linkUrl} target={target}>{titleText}</Link>
                </li>
            );
        })}
    </ul>
);

const MenuDropdown = ({ items }) => (
    <>
        <ButtonIcon
            {...n('userDropdownBtn').withTestId('userDropdown').props}
            type="link"
            icon="angleDown"
            iconPosition="right"
            aria-label="dropdown button"
        />
        {getMenuDropdownItems(items)}
    </>
);

MenuDropdown.propTypes = {
    items: PropTypes.array
};

MenuDropdown.defaultProps = {
    items: []
};

export default MenuDropdown;
