import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Manager } from 'react-popper';
import classnames from 'classnames';

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,
  className: PropTypes.string,
  onToggle: PropTypes.func,
  isSubmenu: PropTypes.bool,
};

const defaultProps = {
  children: undefined,
  className: 'sui-o-dropdown__link',
  onToggle: undefined,
  tag: 'button',
  isSubmenu: false,
};

export const DropdownSubmenuContext = React.createContext({
  handleToggle: () => {},
  isOpen: false,
});
export const useDropdownSubmenuContext = () => React.useContext(DropdownSubmenuContext);

export const DropdownSubmenu = ({
  className,
  onToggle,
  isSubmenu,
  tag: Tag,
  ...attributes
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const classes = classnames(
    className,
    {
      'as--open': isOpen,
      'as--submenu': isSubmenu,
    }
  );

  const handleToggle = (e) => {
    setIsOpen((s) => !s);

    if (onToggle) {
      onToggle(e);
    }
  };

  return (
    <DropdownSubmenuContext.Provider value={{
      handleToggle,
      isOpen,
    }}
    >
      <Manager isSubmenu={isSubmenu}>
        <Tag isSubmenu={isSubmenu} {...attributes} className={classes} />
      </Manager>
    </DropdownSubmenuContext.Provider>
  );
};

DropdownSubmenu.propTypes = propTypes;
DropdownSubmenu.defaultProps = defaultProps;
