import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _typeof from "@babel/runtime/helpers/typeof";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import React from "react";
import { Utils } from "@react-awesome-query-builder/core";
import debounce from "lodash/debounce";
var _Utils$Autocomplete = Utils.Autocomplete,
  mergeListValues = _Utils$Autocomplete.mergeListValues,
  listValueToOption = _Utils$Autocomplete.listValueToOption,
  optionToListValue = _Utils$Autocomplete.optionToListValue,
  optionsToListValues = _Utils$Autocomplete.optionsToListValues,
  fixListValuesGroupOrder = _Utils$Autocomplete.fixListValuesGroupOrder;
var _Utils$ListUtils = Utils.ListUtils,
  mapListValues = _Utils$ListUtils.mapListValues,
  listValuesToArray = _Utils$ListUtils.listValuesToArray,
  getListValue = _Utils$ListUtils.getListValue,
  makeCustomListValue = _Utils$ListUtils.makeCustomListValue,
  searchListValue = _Utils$ListUtils.searchListValue,
  getItemInListValues = _Utils$ListUtils.getItemInListValues;
function sleep(delay) {
  return new Promise(function (resolve) {
    setTimeout(resolve, delay);
  });
}
var useListValuesAutocomplete = function useListValuesAutocomplete(_ref, _ref2) {
  var _config$settings$load, _config$settings$load2, _config$settings$type;
  var asyncFetch = _ref.asyncFetch,
    useLoadMore = _ref.useLoadMore,
    useAsyncSearch = _ref.useAsyncSearch,
    forceAsyncSearch = _ref.forceAsyncSearch,
    fetchSelectedValuesOnInit = _ref.fetchSelectedValuesOnInit,
    selectedAsyncListValues = _ref.asyncListValues,
    staticListValues = _ref.listValues,
    allowCustomValues = _ref.allowCustomValues,
    selectedValue = _ref.value,
    setValue = _ref.setValue,
    placeholder = _ref.placeholder,
    config = _ref.config,
    field = _ref.field;
  var debounceTimeout = _ref2.debounceTimeout,
    multiple = _ref2.multiple,
    uif = _ref2.uif,
    isFieldAutocomplete = _ref2.isFieldAutocomplete;
  var knownSpecialValues = ["LOAD_MORE", "LOADING_MORE"];
  var loadMoreTitle = (_config$settings$load = config.settings.loadMoreLabel) !== null && _config$settings$load !== void 0 ? _config$settings$load : "Load more...";
  var loadingMoreTitle = (_config$settings$load2 = config.settings.loadingMoreLabel) !== null && _config$settings$load2 !== void 0 ? _config$settings$load2 : "Loading more...";
  var aPlaceholder = forceAsyncSearch ? (_config$settings$type = config.settings.typeToSearchLabel) !== null && _config$settings$type !== void 0 ? _config$settings$type : "Type to search" : placeholder;

  // state
  var _React$useState = React.useState(false),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    open = _React$useState2[0],
    setOpen = _React$useState2[1];
  var _React$useState3 = React.useState(undefined),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    asyncFetchMeta = _React$useState4[0],
    setAsyncFetchMeta = _React$useState4[1];
  var _React$useState5 = React.useState(0),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    loadingCnt = _React$useState6[0],
    setLoadingCnt = _React$useState6[1];
  var _React$useState7 = React.useState(false),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    isLoadingMore = _React$useState8[0],
    setIsLoadingMore = _React$useState8[1];
  var _React$useState9 = React.useState(""),
    _React$useState10 = _slicedToArray(_React$useState9, 2),
    inputValue = _React$useState10[0],
    setInputValue = _React$useState10[1];
  var _React$useState11 = React.useState(undefined),
    _React$useState12 = _slicedToArray(_React$useState11, 2),
    asyncListValues = _React$useState12[0],
    setAsyncListValues = _React$useState12[1];

  // ref
  var asyncFectchCnt = React.useRef(0);
  var componentIsMounted = React.useRef(0);
  var isSelectedLoadMore = React.useRef(false);
  var latestSelectedValue = React.useRef();
  latestSelectedValue.current = selectedValue;
  var latestInputValue = React.useRef();
  latestInputValue.current = inputValue;

  // compute
  var nSelectedAsyncListValues = React.useMemo(function () {
    return listValuesToArray(selectedAsyncListValues);
  }, [selectedAsyncListValues]);
  // if selectedAsyncListValues is array of strings/numbers => needs to be resolved
  var areSelectedAsyncListValuesNotResolved = selectedAsyncListValues && Array.isArray(selectedAsyncListValues) && selectedAsyncListValues.filter(function (v) {
    return v !== null && _typeof(v) !== "object";
  }).length > 0;
  var listValues = React.useMemo(function () {
    return asyncFetch ? selectedAsyncListValues ? mergeListValues(asyncListValues, nSelectedAsyncListValues, true) : asyncListValues : listValuesToArray(staticListValues);
  }, [asyncFetch, selectedAsyncListValues, asyncListValues, staticListValues]);
  // todo: useMemo for calcing listValuesToDisplay ?
  var listValuesToDisplay = asyncFetch ? asyncListValues : listValuesToArray(staticListValues);
  if (allowCustomValues && inputValue && !searchListValue(inputValue, asyncListValues)) {
    listValuesToDisplay = mergeListValues(listValuesToDisplay, [makeCustomListValue(inputValue)], true);
  }
  if (asyncFetch && !asyncListValues && selectedAsyncListValues && !inputValue && !open && uif === "antd") {
    // for initial loading, to resolve "a" -> "A"
    listValuesToDisplay = listValues;
  }
  if (asyncFetch && !allowCustomValues && selectedAsyncListValues && uif === "mui") {
    // to prevent warning, when select A, search E -> A is missing in options
    //  MUI: The value provided to Autocomplete is invalid.
    //  None of the options match with `"a"`.
    //  You can use the `isOptionEqualToValue` prop to customize the equality test.
    listValuesToDisplay = mergeListValues(listValuesToDisplay, nSelectedAsyncListValues, true, true);
  }
  //const isDirtyInitialListValues = asyncListValues == undefined && selectedAsyncListValues && selectedAsyncListValues.length && typeof selectedAsyncListValues[0] != "object";
  var isLoading = loadingCnt > 0;
  var canInitialLoadSelected = fetchSelectedValuesOnInit && !open && asyncFetch && areSelectedAsyncListValuesNotResolved && selectedValue != null;
  var canFirstLoadOnOpened = open && asyncFetch && asyncListValues === undefined && (forceAsyncSearch ? inputValue : true);
  var isInitialLoading = (canFirstLoadOnOpened || canInitialLoadSelected) && isLoading;
  var canLoadMore = !isInitialLoading && listValues && listValues.length > 0 && asyncFetchMeta && asyncFetchMeta.hasMore && (asyncFetchMeta.filter || "") === inputValue;
  var canShowLoadMore = !isLoading && canLoadMore;
  var options = mapListValues(listValuesToDisplay, listValueToOption);
  var hasValue = selectedValue != null;
  var selectedListValue = !multiple && hasValue ? getListValue(selectedValue, listValues) : null;
  // const selectedListValues = multiple && hasValue ? selectedValue.map(v => getItemInListValues(listValues, v)) : [];

  // fetch - search
  var fetchListValues = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var filter,
        isLoadMore,
        offset,
        meta,
        newAsyncFetchCnt,
        res,
        isFetchCancelled,
        _ref4,
        values,
        hasMore,
        newMeta,
        nValues,
        assumeHasMore,
        newValues,
        realNewMeta,
        _args = arguments;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            filter = _args.length > 0 && _args[0] !== undefined ? _args[0] : null;
            isLoadMore = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
            // clear obsolete meta
            if (!isLoadMore && asyncFetchMeta) {
              setAsyncFetchMeta(undefined);
            }
            offset = isLoadMore && asyncListValues ? asyncListValues.length : 0;
            meta = isLoadMore && asyncFetchMeta || !useLoadMore && {
              pageSize: 0
            };
            newAsyncFetchCnt = ++asyncFectchCnt.current;
            _context.next = 8;
            return asyncFetch.call(config === null || config === void 0 ? void 0 : config.ctx, filter, offset, meta);
          case 8:
            res = _context.sent;
            isFetchCancelled = asyncFectchCnt.current != newAsyncFetchCnt;
            if (!(isFetchCancelled || !componentIsMounted.current)) {
              _context.next = 12;
              break;
            }
            return _context.abrupt("return", null);
          case 12:
            _ref4 = res !== null && res !== void 0 && res.values ? res : {
              values: res
            }, values = _ref4.values, hasMore = _ref4.hasMore, newMeta = _ref4.meta;
            nValues = listValuesToArray(values);
            if (isLoadMore) {
              newValues = mergeListValues(asyncListValues, nValues, false);
              assumeHasMore = newValues.length > asyncListValues.length;
            } else {
              newValues = nValues;
              if (useLoadMore) {
                assumeHasMore = newValues.length > 0;
              }
            }

            // save new meta
            realNewMeta = hasMore != null || newMeta != null || assumeHasMore != null ? _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, assumeHasMore != null ? {
              hasMore: assumeHasMore
            } : {}), hasMore != null ? {
              hasMore: hasMore
            } : {}), newMeta != null ? newMeta : {}), {}, {
              filter: filter
            }) : undefined;
            if (realNewMeta) {
              setAsyncFetchMeta(realNewMeta);
            }
            return _context.abrupt("return", newValues);
          case 18:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function fetchListValues() {
      return _ref3.apply(this, arguments);
    };
  }();

  // fetch - selected values only
  var fetchSelectedListValues = /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
      var selectedValues, meta, newAsyncFetchCnt, res, isFetchCancelled, _ref6, selectedListValues, latestSelectedValues, nValues;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            selectedValues = latestSelectedValue.current == null ? [] : multiple ? latestSelectedValue.current : [latestSelectedValue.current];
            if (selectedValues.length) {
              _context2.next = 3;
              break;
            }
            return _context2.abrupt("return", null);
          case 3:
            meta = {
              fetchSelectedValues: true
            };
            newAsyncFetchCnt = ++asyncFectchCnt.current;
            _context2.next = 7;
            return asyncFetch.call(config === null || config === void 0 ? void 0 : config.ctx, selectedValues, -1, meta);
          case 7:
            res = _context2.sent;
            isFetchCancelled = asyncFectchCnt.current != newAsyncFetchCnt;
            if (!(isFetchCancelled || !componentIsMounted.current)) {
              _context2.next = 11;
              break;
            }
            return _context2.abrupt("return", null);
          case 11:
            _ref6 = res !== null && res !== void 0 && res.values ? res : {
              values: res
            }, selectedListValues = _ref6.values;
            latestSelectedValues = latestSelectedValue.current == null ? [] : multiple ? latestSelectedValue.current : [latestSelectedValue.current];
            nValues = latestSelectedValues.map(function (v) {
              var _getItemInListValues;
              return (_getItemInListValues = getItemInListValues(selectedListValues, v)) !== null && _getItemInListValues !== void 0 ? _getItemInListValues : makeCustomListValue(v);
            });
            return _context2.abrupt("return", nValues.length ? nValues : null);
          case 15:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function fetchSelectedListValues() {
      return _ref5.apply(this, arguments);
    };
  }();
  var loadSelectedListValues = /*#__PURE__*/function () {
    var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
      var list;
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            setLoadingCnt(function (x) {
              return x + 1;
            });
            _context3.next = 3;
            return fetchSelectedListValues();
          case 3:
            list = _context3.sent;
            if (componentIsMounted.current) {
              _context3.next = 6;
              break;
            }
            return _context3.abrupt("return");
          case 6:
            if (list != null) {
              setValue(latestSelectedValue.current, list);
            }
            setLoadingCnt(function (x) {
              return x - 1;
            });
          case 8:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function loadSelectedListValues() {
      return _ref7.apply(this, arguments);
    };
  }();
  var loadListValues = /*#__PURE__*/function () {
    var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
      var filter,
        isLoadMore,
        list,
        _args4 = arguments;
      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            filter = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : null;
            isLoadMore = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : false;
            setLoadingCnt(function (x) {
              return x + 1;
            });
            setIsLoadingMore(isLoadMore);
            _context4.next = 6;
            return fetchListValues(filter, isLoadMore);
          case 6:
            list = _context4.sent;
            if (componentIsMounted.current) {
              _context4.next = 9;
              break;
            }
            return _context4.abrupt("return");
          case 9:
            if (list != null) {
              // tip: null can be used for reject (eg, if user don't want to filter by input)
              setAsyncListValues(list);
            }
            setLoadingCnt(function (x) {
              return x - 1;
            });
            setIsLoadingMore(false);
          case 12:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }));
    return function loadListValues() {
      return _ref8.apply(this, arguments);
    };
  }();
  var loadListValuesDebounced = React.useCallback(debounce(loadListValues, debounceTimeout), []);
  React.useEffect(function () {
    componentIsMounted.current++;
    // Unmount
    return function () {
      componentIsMounted.current--;
      // if (!componentIsMounted.current && field) {
      //   console.log(`Autocomplete for ${field} has been unmounted`)
      // }
    };
  }, []);
  React.useEffect(function () {
    // Initial loading
    if (canFirstLoadOnOpened && loadingCnt == 0) {
      _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
        return _regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              _context5.next = 2;
              return loadListValues();
            case 2:
            case "end":
              return _context5.stop();
          }
        }, _callee5);
      }))();
    }
    if (canInitialLoadSelected && loadingCnt == 0) {
      _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        return _regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              _context6.next = 2;
              return loadSelectedListValues();
            case 2:
            case "end":
              return _context6.stop();
          }
        }, _callee6);
      }))();
    }
  }, [canFirstLoadOnOpened, canInitialLoadSelected, loadingCnt]);

  // Event handlers
  var onOpen = function onOpen() {
    setOpen(true);
  };
  var onClose = /*#__PURE__*/function () {
    var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(_e) {
      var isLoadMoreClick, resetValue;
      return _regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            isLoadMoreClick = isSelectedLoadMore.current;
            if (isLoadMoreClick) {
              isSelectedLoadMore.current = false;
              if (multiple) {
                // required for MUI
                setOpen(false);
              }
            } else {
              setOpen(false);
            }
            if (!(uif === "mui" && !isLoadMoreClick)) {
              _context7.next = 6;
              break;
            }
            // parity with Antd
            resetValue = "";
            _context7.next = 6;
            return onInputChange(null, resetValue, "my-reset");
          case 6:
          case "end":
            return _context7.stop();
        }
      }, _callee7);
    }));
    return function onClose(_x) {
      return _ref11.apply(this, arguments);
    };
  }();
  var onDropdownVisibleChange = function onDropdownVisibleChange(open) {
    if (open) {
      onOpen();
    } else {
      onClose();
    }
  };
  var isSpecialValue = function isSpecialValue(option) {
    var specialValue = (option === null || option === void 0 ? void 0 : option.specialValue) || (option === null || option === void 0 ? void 0 : option.value);
    return knownSpecialValues.includes(specialValue);
  };
  var onChange = /*#__PURE__*/function () {
    var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(e, val, option) {
      var _option2, _val;
      var isClearingAll, isClearingInput, isClearingSingle, _option$value, _option, specialValue, valHasDuplicates, isBadCallAfterTokenization, shouldIgnore, isAddingCustomOptionFromSearch, _optionsToListValues, _optionsToListValues2, newSelectedValues, newSelectedListValues, _optionToListValue, _optionToListValue2, v, lvs;
      return _regeneratorRuntime.wrap(function _callee8$(_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            // todo: don't rely on 3rd param. check MUI 6
            isClearingAll = multiple && uif === "mui" && option === "clear"; // if user removes all chars in search, don't clear selected value
            isClearingInput = !multiple && uif === "mui" && option === "clear" && (e === null || e === void 0 ? void 0 : e.type) === "change";
            isClearingSingle = !multiple && uif === "mui" && option === "clear" && (e === null || e === void 0 ? void 0 : e.type) !== "change";
            if (uif === "mui") {
              option = val;
              if (multiple) {
                val = option.map(function (o) {
                  var _o$value;
                  return (_o$value = o === null || o === void 0 ? void 0 : o.value) !== null && _o$value !== void 0 ? _o$value : o;
                });
              } else {
                val = (_option$value = (_option = option) === null || _option === void 0 ? void 0 : _option.value) !== null && _option$value !== void 0 ? _option$value : option;
              }
            }
            specialValue = multiple && Array.isArray(option) && option.map(function (opt) {
              return opt === null || opt === void 0 ? void 0 : opt.specialValue;
            }).find(function (v) {
              return !!v;
            }) || ((_option2 = option) === null || _option2 === void 0 ? void 0 : _option2.specialValue);
            if (multiple && val && !Array.isArray(val)) {
              val = [].concat(_toConsumableArray(selectedValue || []), [val]);
              option = null;
            }
            valHasDuplicates = multiple && ((_val = val) === null || _val === void 0 ? void 0 : _val.length) && new Set(val).size !== val.length;
            isBadCallAfterTokenization = multiple && uif === "antd" && e === null && option === null && valHasDuplicates; // if there are tags AND input and select is opened, clear input first
            shouldIgnore = isClearingAll && val.length === 0 && inputValue && open || isClearingInput || isBadCallAfterTokenization;
            if (!shouldIgnore) {
              _context8.next = 11;
              break;
            }
            return _context8.abrupt("return");
          case 11:
            isAddingCustomOptionFromSearch = multiple && val.length && val.length > (selectedValue || []).length && val[val.length - 1] == inputValue && !getListValue(inputValue, asyncListValues);
            if (!(specialValue == "LOAD_MORE")) {
              _context8.next = 19;
              break;
            }
            setInputValue(inputValue);
            isSelectedLoadMore.current = true;
            _context8.next = 17;
            return loadListValues(inputValue, true);
          case 17:
            _context8.next = 39;
            break;
          case 19:
            if (!(specialValue == "LOADING_MORE")) {
              _context8.next = 23;
              break;
            }
            isSelectedLoadMore.current = true;
            _context8.next = 39;
            break;
          case 23:
            if (!multiple) {
              _context8.next = 33;
              break;
            }
            _optionsToListValues = optionsToListValues(val, listValues, allowCustomValues), _optionsToListValues2 = _slicedToArray(_optionsToListValues, 2), newSelectedValues = _optionsToListValues2[0], newSelectedListValues = _optionsToListValues2[1];
            setValue(newSelectedValues, asyncFetch ? newSelectedListValues : undefined);
            if (!isAddingCustomOptionFromSearch) {
              _context8.next = 31;
              break;
            }
            _context8.next = 29;
            return sleep(0);
          case 29:
            _context8.next = 31;
            return onInputChange(null, "", "my-reset");
          case 31:
            _context8.next = 39;
            break;
          case 33:
            _optionToListValue = optionToListValue(val, listValues, allowCustomValues), _optionToListValue2 = _slicedToArray(_optionToListValue, 2), v = _optionToListValue2[0], lvs = _optionToListValue2[1];
            setValue(v, asyncFetch ? lvs : undefined);
            if (!(isClearingSingle && isFieldAutocomplete)) {
              _context8.next = 39;
              break;
            }
            _context8.next = 38;
            return sleep(0);
          case 38:
            setOpen(false);
          case 39:
          case "end":
            return _context8.stop();
        }
      }, _callee8);
    }));
    return function onChange(_x2, _x3, _x4) {
      return _ref12.apply(this, arguments);
    };
  }();
  var onInputChange = /*#__PURE__*/function () {
    var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(e, newInputValue, eventType) {
      var isRemoveOption, isSelectOption, isIgnoredBlur, shouldIgnore, val, canSearchAsync;
      return _regeneratorRuntime.wrap(function _callee9$(_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            // eventType=reset used by MUI on:
            // - (single) initial set, select option - e = null, newInputValue = selected  (+1 call before with e != null)
            // - (single/multi, -ACV) blur - e != null, newInputValue = ''
            // - (multiple v5, -ACV) blur - e = null, newInputValue = '' # unwanted
            // - (multiple) select option - e != null, newInputValue = ''
            // - (multiple v4) delete tag while searching - e = null, newInputValue = ''  # unwanted
            // - (multiple v4) select option while searching - e = null, newInputValue = ''  # unwanted
            isRemoveOption = uif === "mui" && eventType === "removeOption" && newInputValue === "" && multiple;
            isSelectOption = uif === "mui" && eventType === "selectOption" && newInputValue === "" && multiple;
            isIgnoredBlur = uif === "mui" && !multiple && eventType === "blur" && newInputValue === (selectedListValue === null || selectedListValue === void 0 ? void 0 : selectedListValue.title);
            shouldIgnore = uif === "mui" && eventType === "reset"
            // && (
            //   e != null
            //   // for MUI 4 if search "A" and select any option -> should NOT reset search
            //   // for MUI 5 if search "A" and close -> let's hold search but hide, as it's done in antd
            //   || e === null && inputValue && multiple
            // )
            || isSelectOption || isRemoveOption || isIgnoredBlur;
            val = newInputValue;
            if (!(val === loadMoreTitle || val === loadingMoreTitle || shouldIgnore)) {
              _context9.next = 7;
              break;
            }
            return _context9.abrupt("return");
          case 7:
            if (!(uif === "mui" && !multiple && eventType === "selectOption" && newInputValue !== "")) {
              _context9.next = 9;
              break;
            }
            return _context9.abrupt("return");
          case 9:
            if (!(newInputValue != inputValue)) {
              _context9.next = 18;
              break;
            }
            setInputValue(val);
            canSearchAsync = useAsyncSearch && (forceAsyncSearch ? !!val : true);
            if (!canSearchAsync) {
              _context9.next = 17;
              break;
            }
            _context9.next = 15;
            return loadListValuesDebounced(val);
          case 15:
            _context9.next = 18;
            break;
          case 17:
            if (useAsyncSearch && forceAsyncSearch) {
              setAsyncListValues([]);
            }
          case 18:
          case "end":
            return _context9.stop();
        }
      }, _callee9);
    }));
    return function onInputChange(_x5, _x6, _x7) {
      return _ref13.apply(this, arguments);
    };
  }();

  // Options
  var extendOptions = function extendOptions(options) {
    var filtered = _toConsumableArray(options);
    if (useLoadMore) {
      if (canShowLoadMore) {
        filtered.push({
          specialValue: "LOAD_MORE",
          title: loadMoreTitle
        });
      } else if (isLoadingMore) {
        filtered.push({
          specialValue: "LOADING_MORE",
          title: loadingMoreTitle,
          disabled: true
        });
      }
    }
    return filtered;
  };
  var getOptionSelected = function getOptionSelected(option, valueOrOption) {
    if (valueOrOption == null) return null;
    var selectedValue = valueOrOption.value != undefined ? valueOrOption.value : valueOrOption;
    return option.value === selectedValue;
  };
  var getOptionDisabled = function getOptionDisabled(valueOrOption) {
    return valueOrOption && valueOrOption.disabled;
  };
  var getOptionIsCustom = function getOptionIsCustom(valueOrOption) {
    var _valueOrOption$value;
    if (valueOrOption !== null && valueOrOption !== void 0 && valueOrOption.isCustom) return true;
    var val = (_valueOrOption$value = valueOrOption === null || valueOrOption === void 0 ? void 0 : valueOrOption.value) !== null && _valueOrOption$value !== void 0 ? _valueOrOption$value : valueOrOption;
    var lv = getListValue(val, listValues);
    return (lv === null || lv === void 0 ? void 0 : lv.isCustom) || lv == null;
  };
  var getOptionLabel = function getOptionLabel(valueOrOption) {
    if (valueOrOption == null) return null;
    var option = valueOrOption.value != undefined ? valueOrOption : listValueToOption(getListValue(valueOrOption, listValues));
    if (!option && valueOrOption.specialValue) {
      // special last 'Load more...' item
      return valueOrOption.title;
    }
    if (!option && allowCustomValues) {
      // there is just string value, it's not item from list
      return valueOrOption.toString();
    }
    if (!option) {
      // weird
      return valueOrOption.toString();
    }
    return option.title || option.label || option.value.toString(); // fallback to value
  };
  var fixedOptions = uif === "mui" ? fixListValuesGroupOrder(options) : options;
  return {
    options: fixedOptions,
    listValues: listValues,
    hasValue: hasValue,
    selectedListValue: selectedListValue,
    open: open,
    onOpen: onOpen,
    onClose: onClose,
    onDropdownVisibleChange: onDropdownVisibleChange,
    onChange: onChange,
    inputValue: inputValue,
    onInputChange: onInputChange,
    canShowLoadMore: canShowLoadMore,
    isInitialLoading: isInitialLoading,
    isLoading: isLoading,
    isLoadingMore: isLoadingMore,
    isSpecialValue: isSpecialValue,
    extendOptions: extendOptions,
    getOptionSelected: getOptionSelected,
    getOptionDisabled: getOptionDisabled,
    getOptionIsCustom: getOptionIsCustom,
    getOptionLabel: getOptionLabel,
    aPlaceholder: aPlaceholder
  };
};
export default useListValuesAutocomplete;