import React from 'react';
import PropTypes from 'prop-types';
import { Reference } from 'react-popper';
import classnames from 'classnames';
import { useDropdownSubmenuContext } from './DropdownSubmenu';
import { Icon } from '../../atoms/icon/Icon';

const propTypes = {
  children: PropTypes.node,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  className: PropTypes.string,
  /**
   * The function that will be called when the user clicks on the element.
   * This function takes an event as a parameter.
   */
  onClick: PropTypes.func,
};

const defaultProps = {
  children: undefined,
  className: '',
  defaultClassName: 'as--submenu',
  onClick: undefined,
  tag: 'div',
};

export const DropdownSubmenuToggle = ({
  className,
  defaultClassName,
  onClick,
  tag: Tag,
  ...attributes
}) => {
  // TODO: use isOpen to trigger a class that will mimick the hover state
  const { handleToggle, isOpen } = useDropdownSubmenuContext();

  const classes = classnames(
    defaultClassName,
    className,
    isOpen && 'is-open'
  );
  return (
    <Reference>
      {({ ref }) => (
        <>
          <Tag className={classes} onMouseEnter={handleToggle} {...attributes} ref={ref} />
          <Icon name="arrow-right" position="end" size="sm" />
        </>
      )}
    </Reference>
  );
};

DropdownSubmenuToggle.propTypes = propTypes;
DropdownSubmenuToggle.defaultProps = defaultProps;
