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,
};

const defaultProps = {
  children: undefined,
  className: '',
  onToggle: undefined,
  tag: 'div',
};

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

export const Dropdown = ({
  className,
  onToggle,
  tag: Tag,
  ...attributes
}) => {
  const [isOpen, setIsOpen] = useState(false);

  const classes = classnames(
    className
  );

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

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

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

Dropdown.propTypes = propTypes;
Dropdown.defaultProps = defaultProps;
