import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React, { useCallback, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import SpinnerIcon from '@rsuite/icons/legacy/Spinner';
import helper from '../DOMHelper';
import isUndefined from 'lodash/isUndefined';
import isNil from 'lodash/isNil';
import { shallowEqual, useClassNames, mergeRefs, useCustom } from '../utils';
import { DropdownMenuItem } from '../Picker';
import AngleLeftIcon from '@rsuite/icons/legacy/AngleLeft';
import AngleRightIcon from '@rsuite/icons/legacy/AngleRight';
var defaultProps = {
  as: 'div',
  disabledItemValues: [],
  cascadeData: [],
  cascadePaths: [],
  menuWidth: 120,
  menuHeight: 200,
  childrenKey: 'children',
  valueKey: 'value',
  labelKey: 'label'
};
var DropdownMenu = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var Component = props.as,
      activeItemValue = props.activeItemValue,
      classPrefix = props.classPrefix,
      className = props.className,
      childrenKey = props.childrenKey,
      disabledItemValues = props.disabledItemValues,
      menuWidth = props.menuWidth,
      menuHeight = props.menuHeight,
      valueKey = props.valueKey,
      cascadeData = props.cascadeData,
      cascadePaths = props.cascadePaths,
      labelKey = props.labelKey,
      loadingText = props.loadingText,
      renderMenu = props.renderMenu,
      renderMenuItem = props.renderMenuItem,
      onSelect = props.onSelect,
      rest = _objectWithoutPropertiesLoose(props, ["as", "activeItemValue", "classPrefix", "className", "childrenKey", "disabledItemValues", "menuWidth", "menuHeight", "valueKey", "cascadeData", "cascadePaths", "labelKey", "loadingText", "renderMenu", "renderMenuItem", "onSelect"]);

  var _useClassNames = useClassNames(classPrefix),
      merge = _useClassNames.merge,
      prefix = _useClassNames.prefix;

  var classes = merge(className, prefix('items'));
  var rootRef = useRef();
  var rtl = useCustom('DropdownMenu');
  useEffect(function () {
    var _rootRef$current;

    var columns = ((_rootRef$current = rootRef.current) === null || _rootRef$current === void 0 ? void 0 : _rootRef$current.querySelectorAll('[data-type="column"]')) || [];
    columns.forEach(function (column) {
      if (!column) {
        return;
      }

      var activeItem = column.querySelector("." + prefix('item-focus'));

      if (!activeItem) {
        activeItem = column.querySelector("." + prefix('item-active'));
      }

      if (activeItem) {
        var position = helper.getPosition(activeItem, column); // Let the active option scroll into view.

        helper.scrollTop(column, position.top);
      }
    });
  }, [prefix]);
  var getCascadeItems = useCallback(function (items, layer, node, isLeafNode) {
    var data = [];
    var paths = [];

    for (var i = 0; i < cascadeData.length && i < layer; i += 1) {
      data.push(cascadeData[i]);

      if (i < layer - 1 && cascadePaths) {
        paths.push(cascadePaths[i]);
      }
    }

    paths.push(node);

    if (!isLeafNode) {
      data.push(items);
    }

    return {
      cascadeData: data,
      cascadePaths: paths
    };
  }, [cascadeData, cascadePaths]);

  var handleSelect = function handleSelect(layer, node, event) {
    var children = node[childrenKey];
    var isLeafNode = isNil(children);
    var items = (children || []).map(function (item) {
      return _extends({}, item, {
        parent: node
      });
    });

    var _getCascadeItems = getCascadeItems(items, layer + 1, node, isLeafNode),
        cascadeData = _getCascadeItems.cascadeData,
        cascadePaths = _getCascadeItems.cascadePaths;

    onSelect === null || onSelect === void 0 ? void 0 : onSelect(node, cascadeData, cascadePaths, isLeafNode, event);
  };

  var renderCascadeNode = function renderCascadeNode(node, index, layer, focus) {
    var children = node[childrenKey];
    var value = node[valueKey];
    var label = node[labelKey];
    var disabled = disabledItemValues.some(function (disabledValue) {
      return shallowEqual(disabledValue, value);
    }); // Use `value` in keys when If `value` is string or number

    var onlyKey = typeof value === 'number' || typeof value === 'string' ? value : index;
    var Icon = rtl ? AngleRightIcon : AngleLeftIcon;
    return /*#__PURE__*/React.createElement(DropdownMenuItem, {
      classPrefix: "picker-cascader-menu-item",
      as: 'li',
      key: layer + "-" + onlyKey,
      disabled: disabled,
      active: !isUndefined(activeItemValue) && shallowEqual(activeItemValue, value),
      focus: focus,
      value: value,
      className: children ? prefix('has-children') : undefined,
      onSelect: function onSelect(_value, event) {
        return handleSelect(layer, node, event);
      }
    }, renderMenuItem ? renderMenuItem(label, node) : label, children ? /*#__PURE__*/React.createElement(Icon, {
      className: prefix('caret')
    }) : null);
  };

  var styles = {
    width: cascadeData.length * menuWidth
  };
  var cascadeNodes = cascadeData.map(function (children, layer) {
    var onlyKey = layer + "_" + children.length;
    var menu = /*#__PURE__*/React.createElement("ul", {
      role: "listbox"
    }, children.map(function (item, index) {
      return renderCascadeNode(item, index, layer, cascadePaths[layer] && shallowEqual(cascadePaths[layer][valueKey], item[valueKey]));
    }));
    var parentNode = cascadePaths[layer - 1];

    var renderMenuElement = function renderMenuElement() {
      if (renderMenu) {
        return renderMenu(children, menu, parentNode);
      }

      return (parentNode === null || parentNode === void 0 ? void 0 : parentNode.loading) ? /*#__PURE__*/React.createElement("div", {
        className: prefix('column-loading')
      }, /*#__PURE__*/React.createElement(SpinnerIcon, {
        spin: true
      }), " ", /*#__PURE__*/React.createElement("span", null, loadingText)) : menu;
    };

    var node = /*#__PURE__*/React.createElement("div", {
      key: onlyKey,
      className: prefix('column'),
      "data-layer": layer,
      "data-type": 'column',
      style: {
        height: menuHeight,
        width: menuWidth
      }
    }, renderMenuElement());
    return node;
  });
  return /*#__PURE__*/React.createElement(Component, _extends({}, rest, {
    ref: mergeRefs(rootRef, ref),
    className: classes
  }), /*#__PURE__*/React.createElement("div", {
    style: styles
  }, cascadeNodes));
});
export var dropdownMenuPropTypes = {
  classPrefix: PropTypes.string,
  disabledItemValues: PropTypes.array,
  activeItemValue: PropTypes.any,
  childrenKey: PropTypes.string,
  valueKey: PropTypes.string,
  labelKey: PropTypes.string,
  menuWidth: PropTypes.number,
  menuHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  className: PropTypes.string,
  renderMenuItem: PropTypes.func,
  renderMenu: PropTypes.func,
  onSelect: PropTypes.func,
  cascadeData: PropTypes.array,
  cascadePaths: PropTypes.array
};
DropdownMenu.displayName = 'DropdownMenu';
DropdownMenu.defaultProps = defaultProps;
DropdownMenu.propTypes = dropdownMenuPropTypes;
export default DropdownMenu;