import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import * as React from 'react';

var useSelectMenu = function useSelectMenu(props) {
  var id = props.id,
      valid = props.valid,
      invalid = props.invalid,
      expanded = props.expanded,
      defaultExpanded = props.defaultExpanded,
      disabled = props.disabled,
      multiSelect = props.multiSelect,
      onEntry = props.onEntry,
      onExit = props.onExit,
      onToggle = props.onToggle,
      onOptionChange = props.onOptionChange;

  var _React$useState = React.useState(expanded || defaultExpanded || false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      isExpanded = _React$useState2[0],
      setIsExpanded = _React$useState2[1];

  var isExpandedControlled = expanded !== undefined;
  var prevExpanded = React.useRef(); // Handle expanded change when controlled

  React.useEffect(function () {
    if (isExpandedControlled) setIsExpanded(expanded);
  }, [isExpandedControlled, expanded]);
  React.useEffect(function () {
    // Ensure animation fires only
    // when expanded change was detected
    if (!prevExpanded.current || isExpanded !== prevExpanded.current) {
      prevExpanded.current = isExpanded;

      if (isExpanded) {
        onEntry();
      }
    }
  }, [isExpanded, onEntry]);

  if (valid === true && invalid === true) {
    throw {
      name: 'WrongValidation',
      message: 'Select can be either valid or invalid!'
    };
  }

  var handleOptionSelect = function handleOptionSelect(option) {
    onOptionChange(option);
    if (!multiSelect) onOpenChange(false);
  };

  var onOpenChange = function onOpenChange(isOpen) {
    if (disabled) return;

    var handleOpenChange = function handleOpenChange(isOpen) {
      if (isExpandedControlled && onToggle) onToggle(isOpen);else setIsExpanded(isOpen);
    }; // If the component will close
    // we first have to animate its exit before destroying it


    if (!isOpen && onExit) {
      onExit({
        callback: function callback() {
          handleOpenChange(isOpen);
        }
      });
    } else {
      handleOpenChange(isOpen);
    }
  };

  return {
    id: id,
    isExpanded: isExpanded,
    handleOptionSelect: handleOptionSelect,
    onOpenChange: onOpenChange
  };
};

export default useSelectMenu;