"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _faXmark = require("@fortawesome/free-solid-svg-icons/faXmark");
var _fontAwesomeIcon = require("../../font-awesome-icon");
var _multiSelectLabel = _interopRequireDefault(require("./multi-select-label"));
var _useTranslation = require("../../hooks/use-translation");
var _typeahead = _interopRequireDefault(require("../typeahead"));
var _formField = require("../../form-field");
var _button = require("../../button");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function filterSelectedOptions(options, selectedOptions = [], optionLabel = '') {
  // items can contain strings or objects like { [optionLabel]: 'value' }
  const selectedOptionLabels = selectedOptions.map(o => {
    return String(o?.[optionLabel] ?? o);
  });
  if (options && selectedOptionLabels.length && optionLabel) {
    if (Array.isArray(options)) {
      return options.filter(o => !selectedOptionLabels.includes(String(o[optionLabel])));
    }
    if (Object.keys(options).length) {
      return Object.keys(options).reduce((acc, key) => {
        if (Array.isArray(options[key])) {
          return {
            [key]: filterSelectedOptions(options[key], selectedOptionLabels, optionLabel),
            ...acc
          };
        }
        return acc;
      }, {});
    }
  }
  return options;
}
/**
 * @midnight-gray-supported
 * @alpine-light-supported
 */
function MultiSelectTypeahead({
  items = [],
  OptionList,
  optionComponent,
  LabelComponent = _multiSelectLabel.default,
  onDelete = () => {},
  onSearch = () => {},
  onSelect = () => {},
  options = [],
  optionId,
  isDisabled = false,
  autoFocus = false,
  optionLabel = 'label',
  searchFields = [],
  asyncValidation,
  placeholder = '',
  maxItems,
  id = '',
  label = '',
  helperText = '',
  labelTestId,
  labelIcon,
  labelIconTestId = '',
  labelIconTooltipText = '',
  testId,
  helperTextPosition = _formField.HELPER_TEXT_POSITION.TOP,
  containerTestId = 'multi-select-container',
  hasErrored = false,
  showAllOnFocus = false,
  keepInvalidText = false,
  dropdownContentClass = '',
  multiselectContainerClass = '',
  className = '',
  onBlur = () => {},
  onKeyDown = () => {},
  onClearAll = () => {},
  clearAllTooltipText,
  clearAllAriaLabel,
  removeLabelText,
  isClearAllEnabled = false,
  inputRef,
  validity,
  noItemsText,
  invalidItems = [],
  isRequired = false,
  isOptional = false,
  optionalLabelText,
  shouldShowSelectedOptions = false
}) {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  const clearAllTooltipTextWithDefault = clearAllTooltipText ?? t('Clear all');
  const [focused, toggleFocus] = (0, _react.useState)(autoFocus);
  const availableOptions = (0, _react.useMemo)(() => shouldShowSelectedOptions ? options : filterSelectedOptions(options, items, optionLabel), [options, items, optionLabel]);
  const handleFocus = bool => toggleFocus(bool);
  const handleBlur = searchValue => {
    // Only handle blur if necessary for options that should not close dropdown.
    const shouldNotBlur = options.some(opt => opt.shouldNotCloseDropdown);
    if (shouldNotBlur) {
      return;
    }
    toggleFocus(false);
    onBlur(searchValue);
  };
  const handleDelete = (currentValue, index) => {
    for (const opt of options) {
      if (opt.title === currentValue && opt.isDisabled === true) {
        return;
      }
    }
    onDelete(currentValue, index);
  };
  const containerRef = (0, _react.useRef)(null);
  const hasReachedMaxItems = Boolean(maxItems && items.length >= maxItems);
  const validityDisplayLocation = validity?.displayLocation ?? _formField.MESSAGE_DISPLAY_LOCATION.INLINE;
  const showValidationResult = Boolean(validity?.value);
  const showClearAllButton = isClearAllEnabled;
  const isDisabledItem = value => {
    for (const obj of options) {
      if (obj.title === value && obj.isDisabled) {
        return true;
      }
    }
    return false;
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: (0, _classnames.default)('multi-select-typeahead', className),
    children: [label && id && /*#__PURE__*/(0, _jsxRuntime.jsx)(_formField.FormFieldLabel, {
      label: label,
      isDisabled: isDisabled,
      id: id,
      labelTestId: labelTestId,
      labelIcon: labelIcon,
      labelIconTestId: labelIconTestId,
      labelIconTooltipText: labelIconTooltipText,
      isRequired: isRequired,
      isOptional: isOptional,
      optionalLabelText: optionalLabelText ?? t('Optional')
    }), helperText && helperTextPosition === _formField.HELPER_TEXT_POSITION.TOP && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)('helper-text', {
        disabled: isDisabled
      }),
      "test-id": "multi-select-typeahead-helper-text",
      children: helperText
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: (0, _classnames.default)('multi-select-container', multiselectContainerClass, {
        focused: !isDisabled && focused && !hasReachedMaxItems,
        disabled: isDisabled || hasReachedMaxItems,
        error: hasErrored
      }),
      onClick: event => {
        // don't focus if clicked on remove button
        const tagName = event.target.tagName;
        if (['svg', 'path'].includes(tagName)) {
          return;
        }
        handleFocus(true);
      },
      ref: containerRef,
      "test-id": containerTestId,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "multi-select-values",
        children: [items.map((value, index) => /*#__PURE__*/(0, _jsxRuntime.jsx)(LabelComponent, {
          value: value,
          onDelete: currentValue => handleDelete(currentValue, index),
          disabled: isDisabled,
          isReadOnlyItem: isDisabledItem(value),
          isInvalid: invalidItems.includes(value),
          removeLabelText: removeLabelText ?? t('Remove')
        }, index)), /*#__PURE__*/(0, _jsxRuntime.jsx)(_typeahead.default, {
          containerRef: containerRef,
          inputRef: inputRef,
          fieldClass: "multi-select-input",
          placeholder: !!items.length ? '' : placeholder,
          OptionList: OptionList,
          optionComponent: optionComponent,
          onSearch: onSearch,
          onSelect: onSelect,
          onDelete: handleDelete,
          items: items,
          isDisabled: isDisabled || hasReachedMaxItems,
          searchFields: searchFields,
          helperTextPosition: helperTextPosition,
          optionId: optionId,
          optionLabel: optionLabel,
          options: availableOptions,
          isMultiSelect: true,
          focused: focused,
          handleFocus: handleFocus,
          id: id,
          testId: testId,
          showAllOnFocus: showAllOnFocus,
          keepInvalidText: keepInvalidText,
          dropdownContentClass: dropdownContentClass,
          asyncValidation: asyncValidation,
          autoComplete: "off",
          onBlur: handleBlur,
          onKeyDown: onKeyDown,
          noItemsText: noItemsText
        })]
      }), showClearAllButton && !!items.length && !isDisabled && /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.Button, {
        className: "clear-all-button",
        accentType: _button.ACCENT_TYPES.ROUND_ICON,
        size: _button.BUTTON_SIZES.XS,
        onClick: onClearAll,
        tooltipText: clearAllTooltipTextWithDefault,
        "aria-label": clearAllAriaLabel || clearAllTooltipTextWithDefault,
        testId: "clear-all-button",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontAwesomeIcon.FontAwesomeIcon, {
          icon: _faXmark.faXmark
        })
      })]
    }), helperText && helperTextPosition === _formField.HELPER_TEXT_POSITION.BOTTOM && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)('helper-text helper-text-bottom', {
        disabled: isDisabled
      }),
      children: helperText
    }), validity && showValidationResult && validityDisplayLocation === _formField.MESSAGE_DISPLAY_LOCATION.INLINE && /*#__PURE__*/(0, _jsxRuntime.jsx)(_formField.ValidityMessages, {
      validationTestId: 'multi-select-validation',
      validity: validity,
      fieldId: id
    })]
  });
}
var _default = exports.default = MultiSelectTypeahead;