var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

import React from 'react';
import PropTypes from 'prop-types';
import is from 'is';
import classNames from 'classnames';
import ButtonWithIcon from '../../atoms/buttons/ButtonWithIcon';
import DecorativeLink from '../../atoms/links/DecorativeLink';
import Icon from '../../base/Icon';
import './style.css';

var LinkDropdown = function (_React$Component) {
  _inherits(LinkDropdown, _React$Component);

  function LinkDropdown(props) {
    _classCallCheck(this, LinkDropdown);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.handleSelect = function (event) {
      var target = event.target;

      _this.setState({ buttonExpand: false });
      if (is.fn(_this.props.onItemSelect)) {
        _this.props.onItemSelect({ target: target });
      }
    };

    _this.handleClickOutside = function (event) {
      // Close the panel if the user clicks outside the component.
      var node = _this.wrapperRef.current;
      if (node && !node.contains(event.target)) {
        if (_this.state.buttonExpand) {
          _this.closeDropdown();
        }
      }
    };

    _this.handleKeyDown = function (event) {
      // If the user pressed escape collapse list.
      if (event.key === 'Escape') {
        _this.closeDropdown();
      }
    };

    _this.handleClick = function (event) {
      var target = event.target;

      _this.setState(function (prevState) {
        return { buttonExpand: !prevState.buttonExpand };
      });
      if (is.fn(_this.props.onItemSelect)) {
        _this.props.onButtonClick({ target: target });
      }
    };

    _this.state = {
      buttonExpand: false
    };
    _this.wrapperRef = React.createRef();
    _this.setDropDownButtonRef = _this.setDropDownButtonRef.bind(_this);
    _this.closeDropdown = _this.closeDropdown.bind(_this);
    return _this;
  }

  LinkDropdown.prototype.componentDidMount = function componentDidMount() {
    this.buttonClicked = false;
    document.addEventListener('mousedown', this.handleClickOutside);
    this.dropDownButtonRef.addEventListener('mousedown', this.handleRefMouseDown);
  };

  LinkDropdown.prototype.componentWillUnmount = function componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
    this.dropDownButtonRef.removeEventListener('mousedown', this.handleRefMouseDown);
  };

  LinkDropdown.prototype.setDropDownButtonRef = function setDropDownButtonRef(node) {
    this.dropDownButtonRef = node;
  };

  LinkDropdown.prototype.closeDropdown = function closeDropdown() {
    this.setState({ buttonExpand: false });
  };

  LinkDropdown.prototype.render = function render() {
    var _this2 = this;

    var _props = this.props,
        dropdownItems = _props.dropdownItems,
        dropdownButton = _props.dropdownButton;

    var dropdownButtonProps = _extends({}, dropdownButton, {
      onClick: function onClick(e) {
        return _this2.handleClick(e);
      },
      onKeyDown: function onKeyDown(e) {
        return _this2.handleKeyDown(e);
      },
      setButtonRef: this.setDropDownButtonRef,
      expanded: this.state.buttonExpand,
      icon: React.createElement(Icon, { name: 'chevron', svgHeight: 20, svgWidth: 20 }),
      'aria-haspopup': true
    });
    var dropdownClasses = classNames({
      'ma__link-dropdown': true,
      'ma__link-dropdown--expanded': this.state.buttonExpand
    });
    var dropdownMenuClasses = classNames({
      'ma__link-dropdown-menu': true,
      'ma__link-dropdown-menu--expanded': this.state.buttonExpand
    });
    var dropdownItemClasses = classNames({
      'ma__link-dropdown-item': true,
      'ma__link-dropdown-item--expanded': this.state.buttonExpand
    });

    return React.createElement(
      'div',
      { ref: this.wrapperRef, className: dropdownClasses },
      React.createElement(ButtonWithIcon, dropdownButtonProps),
      this.state.buttonExpand && React.createElement(
        'div',
        { className: dropdownMenuClasses, 'aria-labelledby': dropdownButtonProps.id },
        dropdownItems.map(function (item, index) {
          return (
            /* eslint-disable-next-line react/no-array-index-key */
            React.createElement(DecorativeLink, _extends({}, item, { key: item.text + '-' + index, className: dropdownItemClasses, onClick: function onClick(e) {
                return _this2.handleSelect(e);
              } }))
          );
        })
      )
    );
  };

  return LinkDropdown;
}(React.Component);

LinkDropdown.propTypes = process.env.NODE_ENV !== "production" ? {
  /** The props to set up the dropdown button */
  dropdownButton: PropTypes.shape(ButtonWithIcon.propTypes),
  /** Custom callback on dropdown item selection. */
  onItemSelect: PropTypes.func,
  /** Custom callback on dropdown button click. */
  onButtonClick: PropTypes.func,
  /** An array of dropdown link items */
  dropdownItems: PropTypes.arrayOf(PropTypes.shape({
    text: PropTypes.string,
    href: PropTypes.string
  }))
} : {};

LinkDropdown.defaultProps = {
  dropdownButton: {
    text: 'All Organizations',
    capitalized: true,
    size: 'small',
    theme: 'c-primary',
    usage: 'quaternary-simple',
    id: 'dropdownbutton-simple'
  }
};

export default LinkDropdown;