import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _extends from '@babel/runtime/helpers/extends';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.slice.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.string.replace.js';
import React__default, { useRef, Children, useState, useEffect, useLayoutEffect } from 'react';
import PropTypes from 'prop-types';
import { OverflowMenu, OverflowMenuItem } from '@carbon/react';
import classnames from 'classnames';
import { settings } from '../../constants/Settings.js';
import { useResize } from '../../internal/UseResizeObserver.js';
import { Close } from '@carbon/icons-react';

var _excluded = ["children", "i18n"],
  _excluded2 = ["filterTagsOverflowMenuText"];
var DEFAULT_OVERFLOW_TEXT = 'More: {n}';
var getFilterTagsOverflowText = function getFilterTagsOverflowText(filterCount, i18nProp) {
  if (typeof i18nProp === 'function') {
    return i18nProp(filterCount);
  }
  return i18nProp.replace('{n}', filterCount);
};
var prefix = settings.prefix,
  iotPrefix = settings.iotPrefix;
/* eslint-disable-next-line react/prop-types */
var DefaultWrapper = /*#__PURE__*/React__default.forwardRef(function (_ref, ref) {
  var children = _ref.children;
    _ref.i18n;
    var props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React__default.createElement("div", _extends({}, props, {
    ref: ref
  }), children);
});
/* eslint-disable-next-line react/prop-types */
var OverflowTag = function OverflowTag(_ref2) {
  var children = _ref2.children;
  return /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--filtertags-overflow-item__wrapper")
  }, /*#__PURE__*/React__default.createElement("span", null, children), /*#__PURE__*/React__default.createElement(Close, null));
};
var FilterTags = function FilterTags(_ref3) {
  var _overFlowContainerRef3, _overFlowContainerRef4;
  var children = _ref3.children,
    hasOverflow = _ref3.hasOverflow,
    id = _ref3.id,
    tagContainer = _ref3.tagContainer,
    onChange = _ref3.onChange,
    i18nProps = _ref3.i18n,
    testId = _ref3.testId;
  var TagContainer = tagContainer || DefaultWrapper;
  var overFlowContainerRef = useRef(null);
  useResize(overFlowContainerRef);
  var childrenItems = Children.map(children, function (child) {
    return child;
  });
  var breakingWidth = useRef([]);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    overflowItems = _useState2[0],
    setOverflowItems = _useState2[1];
  var _useState3 = useState(childrenItems),
    _useState4 = _slicedToArray(_useState3, 2),
    visibleItems = _useState4[0],
    setVisibleItems = _useState4[1];
  var _i18nProps$filterTags = i18nProps.filterTagsOverflowMenuText,
    filterTagsOverflowMenuText = _i18nProps$filterTags === void 0 ? DEFAULT_OVERFLOW_TEXT : _i18nProps$filterTags,
    i18n = _objectWithoutProperties(i18nProps, _excluded2);
  useEffect(function () {
    if (hasOverflow && overFlowContainerRef) {
      setOverflowItems([]);
      setVisibleItems(childrenItems.slice(0));
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [children]);
  useLayoutEffect(function () {
    if (hasOverflow && overFlowContainerRef.current) {
      var _overFlowContainerRef, _overFlowContainerRef2;
      var clientWidth = (_overFlowContainerRef = overFlowContainerRef.current) === null || _overFlowContainerRef === void 0 ? void 0 : _overFlowContainerRef.clientWidth;
      var scrollWidth = (_overFlowContainerRef2 = overFlowContainerRef.current) === null || _overFlowContainerRef2 === void 0 ? void 0 : _overFlowContainerRef2.scrollWidth;
      var currBreakingWidth = breakingWidth.current;
      var breakingWidthLength = currBreakingWidth.length;
      var tooBig = scrollWidth > clientWidth;
      if (tooBig) {
        currBreakingWidth.push(scrollWidth);
        if (visibleItems.length > 1) {
          // Move item to the hidden list
          setOverflowItems([visibleItems.pop()].concat(_toConsumableArray(overflowItems)));
          setVisibleItems(_toConsumableArray(visibleItems));
        }
      } else if (currBreakingWidth[breakingWidthLength - 1] >= 0 && clientWidth > currBreakingWidth[breakingWidthLength - 1] && overflowItems.length > 0) {
        // Move the item to the visible list
        setVisibleItems([].concat(_toConsumableArray(visibleItems), [overflowItems.shift()]));
        setOverflowItems(_toConsumableArray(overflowItems));
        currBreakingWidth.shift();
      }
    }
  } /* eslint-disable react-hooks/exhaustive-deps */, [overFlowContainerRef === null || overFlowContainerRef === void 0 || (_overFlowContainerRef3 = overFlowContainerRef.current) === null || _overFlowContainerRef3 === void 0 ? void 0 : _overFlowContainerRef3.scrollWidth, overFlowContainerRef === null || overFlowContainerRef === void 0 || (_overFlowContainerRef4 = overFlowContainerRef.current) === null || _overFlowContainerRef4 === void 0 ? void 0 : _overFlowContainerRef4.clientWidth, childrenItems]
  /* eslint-enable react-hooks/exhaustive-deps */);
  return /*#__PURE__*/React__default.createElement(TagContainer, {
    key: "".concat(hasOverflow, "-Tag-Container"),
    id: id
    // TODO: remove id in v3
    ,
    "data-testid": id || testId,
    className: classnames("".concat(iotPrefix, "--filtertags-container"), _defineProperty({}, "".concat(iotPrefix, "--filtertags-container__wrap"), hasOverflow)),
    ref: overFlowContainerRef,
    onChange: onChange,
    i18n: i18n
  }, visibleItems, overflowItems.length > 0 && /*#__PURE__*/React__default.createElement(OverflowMenu, {
    "data-floating-menu-container": true,
    className: "".concat(iotPrefix, "--filtertags-overflow-menu"),
    renderIcon: function renderIcon() {
      return /*#__PURE__*/React__default.createElement("div", {
        className: "".concat(prefix, "--tag")
      }, getFilterTagsOverflowText(overflowItems.length, filterTagsOverflowMenuText));
    },
    menuOptionsClass: "".concat(iotPrefix, "--filtertags-overflow-items"),
    menuOffset: {
      top: 15
    },
    "data-testid": "".concat(testId, "-overflow-menu")
  }, overflowItems.map(function (child, i) {
    return /*#__PURE__*/React__default.createElement(OverflowMenuItem, {
      "data-testid": "".concat(testId, "-overflow-menu-item-").concat(i),
      className: "".concat(iotPrefix, "--filtertags-overflow-item"),
      title: child.props.children,
      key: "".concat(child.props.children, "-").concat(i),
      onClick: child.props.onClose,
      itemText: /*#__PURE__*/React__default.createElement(OverflowTag, null, child.props.children)
    });
  })));
};
var propTypes = {
  /**
   * ID for filter tag container
   */
  id: PropTypes.string,
  /**
   * Tag components nested inside Filter tag component
   */
  children: PropTypes.node.isRequired,
  /**
   * Bit to determine if tags collapse into overflow tag
   */
  hasOverflow: PropTypes.bool,
  /**
   * Optional container for filter tags
   */
  tagContainer: PropTypes.elementType,
  /**
   * OnChange handled passed to the tagContainer
   */
  onChange: PropTypes.func,
  /**
   * This is an object of {[key: string]: string}, but it's
   * unknown what they are as it's dependent on the tagContainer
   */
  // eslint-disable-next-line react/forbid-prop-types
  i18n: PropTypes.object,
  testId: PropTypes.string
};
var defaultProps = {
  id: 'filter-tag-container',
  hasOverflow: true,
  tagContainer: null,
  onChange: null,
  i18n: {
    filterTagsOverflowMenuText: DEFAULT_OVERFLOW_TEXT
  },
  testId: 'filter-tags'
};
FilterTags.propTypes = propTypes;
FilterTags.defaultProps = defaultProps;
FilterTags.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "FilterTags",
  "props": {
    "id": {
      "defaultValue": {
        "value": "'filter-tag-container'",
        "computed": false
      },
      "description": "ID for filter tag container",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hasOverflow": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "Bit to determine if tags collapse into overflow tag",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "tagContainer": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Optional container for filter tags",
      "type": {
        "name": "elementType"
      },
      "required": false
    },
    "onChange": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "OnChange handled passed to the tagContainer",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  filterTagsOverflowMenuText: DEFAULT_OVERFLOW_TEXT,\n}",
        "computed": false
      },
      "description": "This is an object of {[key: string]: string}, but it's\nunknown what they are as it's dependent on the tagContainer",
      "type": {
        "name": "object"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'filter-tags'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "children": {
      "description": "Tag components nested inside Filter tag component",
      "type": {
        "name": "node"
      },
      "required": true
    }
  }
};
var FilterTags$1 = FilterTags;

export { FilterTags$1 as default };
