import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import * as React from 'react';
import { useFloating, useInteractions, useClick, useDismiss, useListNavigation, shift, offset, size, useTransitionStatus, useRole, flip } from '@floating-ui/react';
var CONTAINER_MARGIN = 10;
var MAX_POPUP_WIDTH = 320;

var useFloatingSelectMenu = function useFloatingSelectMenu(props) {
  var isExpanded = props.isExpanded,
      onOpenChange = props.onOpenChange;

  var _React$useState = React.useState(null),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      activeIndex = _React$useState2[0],
      setActiveIndex = _React$useState2[1];

  var listRef = React.useRef([]);

  var _useFloating = useFloating({
    open: isExpanded,
    placement: 'bottom-start',
    onOpenChange: onOpenChange,
    middleware: [offset(8), flip(), // Apply shift when we want to move component to the side to fit
    shift(), size({
      apply: function apply(_ref) {
        var elements = _ref.elements,
            availableHeight = _ref.availableHeight,
            availableWidth = _ref.availableWidth;
        Object.assign(elements.floating.style, {
          maxHeight: "".concat(availableHeight - CONTAINER_MARGIN, "px"),
          maxWidth: "".concat(Math.min(availableWidth, MAX_POPUP_WIDTH), "px") // the max width cannot be wider than 320px

        });
      }
    })]
  }),
      x = _useFloating.x,
      y = _useFloating.y,
      strategy = _useFloating.strategy,
      refs = _useFloating.refs,
      context = _useFloating.context,
      placement = _useFloating.placement;

  var _useTransitionStatus = useTransitionStatus(context, {
    duration: {
      open: 320,
      close: 250
    }
  }),
      isMounted = _useTransitionStatus.isMounted,
      status = _useTransitionStatus.status;

  var click = useClick(context);
  var dismiss = useDismiss(context, {
    referencePress: true,
    referencePressEvent: 'click'
  });
  var role = useRole(context, {
    role: 'listbox'
  });
  var listNav = useListNavigation(context, {
    listRef: listRef,
    activeIndex: activeIndex,
    onNavigate: setActiveIndex,
    // This is a large list, allow looping.
    loop: true,
    focusItemOnHover: false
  });

  var _useInteractions = useInteractions([click, dismiss, role, listNav]),
      getReferenceProps = _useInteractions.getReferenceProps,
      getFloatingProps = _useInteractions.getFloatingProps,
      getItemProps = _useInteractions.getItemProps;

  return {
    interactions: {
      getReferenceProps: getReferenceProps,
      getFloatingProps: getFloatingProps,
      getItemProps: getItemProps
    },
    floatingProps: {
      x: x,
      y: y,
      strategy: strategy,
      placement: placement
    },
    refs: refs,
    listRef: listRef,
    context: context,
    isMounted: isMounted,
    status: status,
    activeIndex: activeIndex
  };
};

export default useFloatingSelectMenu;