import React from 'react';
import PropTypes from 'prop-types';
import { Dropdown, Box } from '@ui/components';

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

const MenuItem = props => {
  const { children, className, color, openAt, disabled, icon, onClick, value, TagName, ...attrs } = props;
  const isSubMenu = Array.isArray(children);
  const content = isSubMenu ? children[0] : children;
  const MenuItemClasses = [
    'Menu-Item',
    className,
    color && `Menu-Item_${color}`,
    disabled && 'Menu-Item_link_disabled',
    isSubMenu && 'Menu-Item_arrow',
    TagName === 'a' && 'Menu-Item_link',
  ]
    .filter(e => e)
    .join(' ');

  const handleFocus = e => e.stopPropagation();

  const handleKeyDown = e => {
    if (e.which !== 32 && e.which !== 13) return; // only fire onClick on space and enter
    if (typeof onClick === 'function') onClick(e);
  };

  if (isSubMenu) {
    return (
      <Dropdown justify={openAt} trigger="hover">
        <div {...attrs} className={MenuItemClasses} role="button" tabIndex={0}>
          {icon && <i className={icon} />}
          {content}
        </div>
        <Box bem={[['pop']]} className={`Menu-Item-SubMenu Menu-Item-SubMenu_${openAt}`}>
          {children[1]}
        </Box>
      </Dropdown>
    );
  }

  return (
    <div
      {...attrs}
      {...(onClick && { onClick, onFocus: handleFocus, onKeyDown: handleKeyDown })}
      {...((onClick || TagName === 'a') && { role: 'button', tabIndex: 0 })}
      className={MenuItemClasses}
    >
      {icon && <i className={icon} />}
      {content}
    </div>
  );
};

MenuItem.propTypes = {
  children: PropTypes.any,
  className: PropTypes.string,
  color: PropTypes.oneOf(['blue', 'green', 'purple', 'red', 'yellow']),
  disabled: PropTypes.bool,
  icon: PropTypes.string,
  onClick: PropTypes.func,
  openAt: PropTypes.oneOf(['left', 'right']),
  TagName: PropTypes.string,
  value: PropTypes.any,
};

MenuItem.defaultProps = {
  className: '',
  openAt: 'right',
  TagName: 'a',
};

export default MenuItem;
