'use strict';

exports.__esModule = true;

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _is = require('is');

var _is2 = _interopRequireDefault(_is);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _ButtonWithIcon = require('../../atoms/buttons/ButtonWithIcon');

var _ButtonWithIcon2 = _interopRequireDefault(_ButtonWithIcon);

var _DecorativeLink = require('../../atoms/links/DecorativeLink');

var _DecorativeLink2 = _interopRequireDefault(_DecorativeLink);

var _Icon = require('../../base/Icon');

var _Icon2 = _interopRequireDefault(_Icon);

require('./style.css');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

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 (_is2.default.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 (_is2.default.fn(_this.props.onItemSelect)) {
        _this.props.onButtonClick({ target: target });
      }
    };

    _this.state = {
      buttonExpand: false
    };
    _this.wrapperRef = _react2.default.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: _react2.default.createElement(_Icon2.default, { name: 'chevron', svgHeight: 20, svgWidth: 20 }),
      'aria-haspopup': true
    });
    var dropdownClasses = (0, _classnames2.default)({
      'ma__link-dropdown': true,
      'ma__link-dropdown--expanded': this.state.buttonExpand
    });
    var dropdownMenuClasses = (0, _classnames2.default)({
      'ma__link-dropdown-menu': true,
      'ma__link-dropdown-menu--expanded': this.state.buttonExpand
    });
    var dropdownItemClasses = (0, _classnames2.default)({
      'ma__link-dropdown-item': true,
      'ma__link-dropdown-item--expanded': this.state.buttonExpand
    });

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

  return LinkDropdown;
}(_react2.default.Component);

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

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

exports.default = LinkDropdown;
module.exports = exports['default'];