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 ButtonWithIcon from '../../atoms/buttons/ButtonWithIcon';
import InputTextTypeAhead from '../InputTextTypeAhead';
import Icon from '../../base/Icon';
import './style.css';

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

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

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

    _this.state = {
      buttonText: _this.props.dropdownButton.text,
      buttonExpand: false
    };

    _this.wrapperRef = React.createRef();
    _this.setDropDownButtonRef = _this.setDropDownButtonRef.bind(_this);
    _this.handleRefMouseDown = _this.handleRefMouseDown.bind(_this);

    _this.closeDropdown = _this.closeDropdown.bind(_this);
    _this.handleClick = _this.handleClick.bind(_this);
    _this.handleKeyDown = _this.handleKeyDown.bind(_this);
    _this.handleInputBlur = _this.handleInputBlur.bind(_this);
    _this.handleSelect = _this.handleSelect.bind(_this);
    _this.handleClickOutside = _this.handleClickOutside.bind(_this);
    return _this;
  }

  TypeAheadDropdown.prototype.componentDidMount = function componentDidMount() {
    this.buttonClicked = false;

    document.addEventListener('mousedown', this.handleClickOutside);
    this.dropDownButtonRef.addEventListener('mousedown', this.handleRefMouseDown);
  };

  TypeAheadDropdown.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var selectedValue = nextProps.inputText.selected;
    if (selectedValue !== undefined) {
      this.setState({
        buttonText: selectedValue,
        buttonExpand: false
      });
    }
  };

  TypeAheadDropdown.prototype.componentDidUpdate = function componentDidUpdate() {
    this.buttonClicked = false;
  };

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

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

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

  TypeAheadDropdown.prototype.handleRefMouseDown = function handleRefMouseDown() {
    this.buttonClicked = true;
  };

  TypeAheadDropdown.prototype.handleClick = function handleClick() {
    this.setState(function (prevState) {
      return { buttonExpand: !prevState.buttonExpand };
    });
  };

  TypeAheadDropdown.prototype.handleKeyDown = function handleKeyDown(event) {
    // If the user pressed escape, or pressed enter with nothing selected close
    // the panel.
    if (event.key === 'Escape' || event.key === 'Enter' && event.target.value === '') {
      this.closeDropdown();
    }
    if (event.key === 'Escape' && this.dropDownButtonRef) {
      this.dropDownButtonRef.focus();
    }
    if (typeof this.props.onKeyDown === 'function') {
      this.props.onKeyDown(event);
    }
  };

  TypeAheadDropdown.prototype.handleInputBlur = function handleInputBlur() {
    if (!this.buttonClicked) {
      this.closeDropdown();
    }
  };

  TypeAheadDropdown.prototype.handleSelect = function handleSelect(event, input) {
    // Stop the filters form submission if enter is pressed in the selector.
    event.preventDefault();
    // Update this component state and pass the event out to the calling code.
    if (input.suggestion.text !== '') {
      this.setState({
        buttonText: input.suggestion.text,
        buttonExpand: false
      });
      if (typeof this.props.inputText.onChange === 'function') {
        this.props.inputText.onChange(event, input);
      }
    }
  };

  TypeAheadDropdown.prototype.handleClickOutside = function handleClickOutside(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.setState({ buttonExpand: false });
      }
    }
  };

  TypeAheadDropdown.prototype.render = function render() {
    var dropdownButton = _extends({
      onClick: this.handleClick,
      setButtonRef: this.setDropDownButtonRef,
      expanded: this.state.buttonExpand,
      icon: React.createElement(Icon, { name: 'chevron', svgHeight: 20, svgWidth: 20 }),
      size: ''
    }, this.props.dropdownButton);
    dropdownButton.text = this.state.buttonText || 'All Organizations';

    var inputTextTypeAheadProps = _extends({}, this.props.inputText, {
      onKeyDown: this.handleKeyDown,
      onChange: this.handleSelect,
      onBlur: this.handleInputBlur,
      autoFocusInput: true
    });

    return React.createElement(
      'div',
      { ref: this.wrapperRef },
      React.createElement(ButtonWithIcon, dropdownButton),
      this.state.buttonExpand && React.createElement(InputTextTypeAhead, inputTextTypeAheadProps)
    );
  };

  return TypeAheadDropdown;
}(React.Component);

TypeAheadDropdown.propTypes = process.env.NODE_ENV !== "production" ? {
  /** The props to set up the dropdown button */
  dropdownButton: PropTypes.shape(ButtonWithIcon.propTypes).isRequired,
  /** The props to set up the inputTextTypeAhead */
  inputText: PropTypes.shape(InputTextTypeAhead.propTypes).isRequired,
  /** Custom keydown callback */
  onKeyDown: PropTypes.func
} : {};

export default TypeAheadDropdown;