/* eslint-env browser */

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { Popper } from 'react-popper';
import FocusLock from 'react-focus-lock';
import classnames from 'classnames';
import { useDropdownContext } from './Dropdown';
import { ClickAwayListener } from '../../helpers/clickAwayListener/ClickAwayListener';

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,
  popperProps: PropTypes.object,
  clickAwayListenerProps: PropTypes.object,
};

const defaultProps = {
  children: undefined,
  className: '',
  defaultClassName: 'sui-o-dropdown',
  tag: 'div',
  popperProps: { placement: 'bottom-start' },
  clickAwayListenerProps: {},
};

export const DropdownMenu = ({
  tag: Tag,
  defaultClassName,
  className,
  popperProps,
  clickAwayListenerProps,
  ...attributes
}) => {
  const { isOpen, handleToggle } = useDropdownContext();

  const classes = classnames(
    defaultClassName,
    className,
    {
      'as--open': isOpen,
    }
  );

  if (!isOpen) {
    return '';
  }

  return (
    ReactDOM.createPortal((
      <Popper {...popperProps}>
        {({ placement, ref, style }) => (
          <ClickAwayListener onClickOutside={handleToggle} {...clickAwayListenerProps}>
            <FocusLock autoFocus={false}>
              <Tag ref={ref} style={style} data-placement={placement} className={classes} role="menu" {...attributes} />
            </FocusLock>
          </ClickAwayListener>
        )}
      </Popper>
    ), document.body)
  );
};

DropdownMenu.propTypes = propTypes;
DropdownMenu.defaultProps = defaultProps;
