import { t } from '@grafana/i18n';
import React, { forwardRef, useState, useRef, useId, useMemo, useCallback, useImperativeHandle, useEffect, useLayoutEffect } from 'react';
import { FloatingPortal, FloatingFocusManager } from '@floating-ui/react';
import { useStyles2, Spinner, Text } from '@grafana/ui';
import { css, cx } from '@emotion/css';
import { isMultiValueOperator, OPERATORS, isFilterComplete } from '../AdHocFiltersVariable.js';
import { useVirtualizer } from '@tanstack/react-virtual';
import { LoadingOptionsPlaceholder, OptionsErrorPlaceholder, NoOptionsPlaceholder, DropdownItem, MultiValueApplyButton } from './DropdownItem.js';
import { flattenOptionGroups, setupDropdownAccessibility, VIRTUAL_LIST_OVERSCAN, VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION, VIRTUAL_LIST_ITEM_HEIGHT, switchInputType, generateFilterUpdatePayload, populateInputValueOnInputTypeSwitch, switchToNextInputType, generatePlaceholder, ERROR_STATE_DROPDOWN_WIDTH } from './utils.js';
import { handleOptionGroups } from '../../utils.js';
import { useFloatingInteractions, MAX_MENU_HEIGHT } from './useFloatingInteractions.js';
import { MultiValuePill } from './MultiValuePill.js';
import { getAdhocOptionSearcher } from '../getAdhocOptionSearcher.js';
import { FILTER_CHANGED_INTERACTION, ADHOC_KEYS_DROPDOWN_INTERACTION, ADHOC_VALUES_DROPDOWN_INTERACTION, FILTER_REMOVED_INTERACTION } from '../../../performance/interactionConstants.js';

const AdHocCombobox = forwardRef(function AdHocCombobox2({
  filter,
  controller,
  isAlwaysWip,
  handleChangeViewMode,
  focusOnWipInputRef,
  populateInputOnEdit,
  onInputClick
}, parentRef) {
  var _a, _b, _c;
  const [open, setOpen] = useState(false);
  const [options, setOptions] = useState([]);
  const [optionsLoading, setOptionsLoading] = useState(false);
  const [optionsError, setOptionsError] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [activeIndex, setActiveIndex] = useState(null);
  const [filterInputType, setInputType] = useState(!isAlwaysWip ? "value" : "key");
  const [preventFiltering, setPreventFiltering] = useState(!isAlwaysWip && filterInputType === "value");
  const styles = useStyles2(getStyles);
  const [filterMultiValues, setFilterMultiValues] = useState([]);
  const [_, setForceRefresh] = useState({});
  const { allowCustomValue = true, onAddCustomValue, filters, inputPlaceholder } = controller.useState();
  const multiValuePillWrapperRef = useRef(null);
  const hasMultiValueOperator = isMultiValueOperator((filter == null ? void 0 : filter.operator) || "");
  const isMultiValueEdit = hasMultiValueOperator && filterInputType === "value";
  const operatorIdentifier = useId();
  const listRef = useRef([]);
  const disabledIndicesRef = useRef([]);
  const filterInputTypeRef = useRef(!isAlwaysWip ? "value" : "key");
  const optionsSearcher = useMemo(() => getAdhocOptionSearcher(options), [options]);
  const isLastFilter = useMemo(() => {
    if (isAlwaysWip) {
      return false;
    }
    if (filters.at(-1) === filter) {
      return true;
    }
    return false;
  }, [filter, isAlwaysWip, filters]);
  const handleResetWip = useCallback(() => {
    if (isAlwaysWip) {
      controller.addWip();
      setInputType("key");
      setInputValue("");
    }
  }, [controller, isAlwaysWip]);
  const handleMultiValueFilterCommit = useCallback(
    (controller2, filter2, filterMultiValues2, preventFocus) => {
      var _a2;
      if (!filterMultiValues2.length && filter2.origin) {
        controller2.updateToMatchAll(filter2);
      }
      if (filterMultiValues2.length) {
        const valueLabels = [];
        const values = [];
        filterMultiValues2.forEach((item) => {
          var _a3;
          valueLabels.push((_a3 = item.label) != null ? _a3 : item.value);
          values.push(item.value);
        });
        let shouldUpdate = true;
        if (Array.isArray(filter2.values) && filter2.values.length === values.length) {
          shouldUpdate = !filter2.values.every((v, i) => v === values[i]);
        }
        if (shouldUpdate) {
          (_a2 = controller2.startProfile) == null ? void 0 : _a2.call(controller2, FILTER_CHANGED_INTERACTION);
        }
        controller2.updateFilter(filter2, { valueLabels, values, value: values[0] });
        setFilterMultiValues([]);
      }
      if (!preventFocus) {
        setTimeout(() => {
          var _a3;
          return (_a3 = refs.domReference.current) == null ? void 0 : _a3.focus();
        });
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );
  const handleLocalMultiValueChange = useCallback((selectedItem) => {
    setFilterMultiValues((items) => {
      if (items.some((item) => item.value === selectedItem.value)) {
        return items.filter((item) => item.value !== selectedItem.value);
      }
      return [...items, selectedItem];
    });
  }, []);
  const onOpenChange = useCallback(
    (nextOpen, _2, reason) => {
      setOpen(nextOpen);
      if (reason && ["outside-press", "escape-key"].includes(reason)) {
        if (isMultiValueEdit) {
          handleMultiValueFilterCommit(controller, filter, filterMultiValues);
        } else {
          if (filter && filter.origin && inputValue === "") {
            controller.updateToMatchAll(filter);
          }
        }
        handleResetWip();
        handleChangeViewMode == null ? void 0 : handleChangeViewMode();
      }
    },
    [
      filter,
      filterMultiValues,
      handleChangeViewMode,
      handleMultiValueFilterCommit,
      handleResetWip,
      inputValue,
      isMultiValueEdit,
      controller
    ]
  );
  const outsidePressIdsToIgnore = useMemo(() => {
    return [
      operatorIdentifier,
      ...filterMultiValues.reduce(
        (acc, item, i) => [...acc, `${item.value}-${i}`, `${item.value}-${i}-close-icon`],
        []
      )
    ];
  }, [operatorIdentifier, filterMultiValues]);
  const { refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps } = useFloatingInteractions({
    open,
    onOpenChange,
    activeIndex,
    setActiveIndex,
    outsidePressIdsToIgnore,
    listRef,
    disabledIndicesRef
  });
  useImperativeHandle(parentRef, () => () => {
    var _a2;
    return (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();
  }, [refs.domReference]);
  function onChange(event) {
    const value = event.target.value;
    setInputValue(value);
    const nextFilteredItems = flattenOptionGroups(handleOptionGroups(optionsSearcher(value)));
    if (!nextFilteredItems.length && allowCustomValue) {
      setActiveIndex(0);
    } else {
      setActiveIndex(getFirstSelectableIndex(nextFilteredItems));
    }
    if (preventFiltering) {
      setPreventFiltering(false);
    }
  }
  const handleRemoveMultiValue = useCallback(
    (item) => {
      setFilterMultiValues((selected) => selected.filter((option) => option.value !== item.value));
      setTimeout(() => {
        var _a2;
        return (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();
      });
    },
    [refs.domReference]
  );
  const filteredDropDownItems = flattenOptionGroups(
    handleOptionGroups(optionsSearcher(preventFiltering ? "" : inputValue))
  );
  const getFirstSelectableIndex = useCallback((items) => {
    const index = items.findIndex((item) => !item.options);
    return index >= 0 ? index : null;
  }, []);
  if (allowCustomValue && filterInputType !== "operator" && inputValue) {
    const operatorDefinition = OPERATORS.find((op) => (filter == null ? void 0 : filter.operator) === op.value);
    const customOptionValue = {
      value: inputValue.trim(),
      label: inputValue.trim(),
      isCustom: true
    };
    if (operatorDefinition == null ? void 0 : operatorDefinition.isRegex) {
      filteredDropDownItems.unshift(customOptionValue);
    } else {
      filteredDropDownItems.push(customOptionValue);
    }
  }
  const maxOptionWidth = setupDropdownAccessibility(filteredDropDownItems, listRef, disabledIndicesRef);
  const handleFetchOptions = useCallback(
    async (inputType) => {
      var _a2, _b2, _c2, _d;
      const interactionName = inputType === "key" ? ADHOC_KEYS_DROPDOWN_INTERACTION : ADHOC_VALUES_DROPDOWN_INTERACTION;
      if (inputType !== "operator") {
        (_a2 = controller.startInteraction) == null ? void 0 : _a2.call(controller, interactionName);
      }
      setOptionsError(false);
      setOptionsLoading(true);
      setOptions([]);
      let options2 = [];
      try {
        if (inputType === "key") {
          options2 = await controller.getKeys(null);
        } else if (inputType === "operator") {
          options2 = controller.getOperators();
        } else if (inputType === "value") {
          options2 = await controller.getValuesFor(filter);
        }
        if (filterInputTypeRef.current !== inputType) {
          (_b2 = controller.stopInteraction) == null ? void 0 : _b2.call(controller);
          return;
        }
        setOptions(options2);
        if ((_c2 = options2[0]) == null ? void 0 : _c2.group) {
          setActiveIndex(1);
        } else {
          setActiveIndex(0);
        }
      } catch (e) {
        setOptionsError(true);
      }
      setOptionsLoading(false);
      (_d = controller.stopInteraction) == null ? void 0 : _d.call(controller);
    },
    [filter, controller]
  );
  const rowVirtualizer = useVirtualizer({
    count: filteredDropDownItems.length,
    getScrollElement: () => refs.floating.current,
    estimateSize: (index) => filteredDropDownItems[index].description ? VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION : VIRTUAL_LIST_ITEM_HEIGHT,
    overscan: VIRTUAL_LIST_OVERSCAN
  });
  const handleBackspaceInput = useCallback(
    (event, multiValueEdit) => {
      var _a2;
      if (event.key === "Backspace" && !inputValue) {
        if (filterInputType === "value") {
          if (multiValueEdit) {
            if (filterMultiValues.length) {
              setFilterMultiValues((items) => {
                const updated = [...items];
                updated.splice(-1, 1);
                return updated;
              });
              return;
            }
          }
          if (filter == null ? void 0 : filter.origin) {
            return;
          }
          setInputType("operator");
          return;
        }
        if (filterInputType === "operator") {
          event.preventDefault();
          setInputValue("");
          if (filter) {
            controller.updateFilter(filter, {
              key: "",
              keyLabel: "",
              operator: "",
              value: "",
              valueLabels: [],
              values: void 0
            });
          }
          switchInputType("key", setInputType, void 0, refs.domReference.current);
          return;
        }
        focusOnWipInputRef == null ? void 0 : focusOnWipInputRef();
        if (isFilterComplete(filter)) {
          (_a2 = controller.startProfile) == null ? void 0 : _a2.call(controller, FILTER_REMOVED_INTERACTION);
        }
        setOpen(false);
        controller.handleComboboxBackspace(filter);
        if (isAlwaysWip) {
          handleResetWip();
        }
      }
    },
    [
      inputValue,
      filterInputType,
      focusOnWipInputRef,
      filter,
      controller,
      isAlwaysWip,
      filterMultiValues.length,
      refs.domReference,
      handleResetWip
    ]
  );
  const handleTabInput = useCallback(
    (event, multiValueEdit) => {
      var _a2;
      if (event.key === "Tab" && !event.shiftKey) {
        if (multiValueEdit) {
          event.preventDefault();
          handleMultiValueFilterCommit(controller, filter, filterMultiValues);
          (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();
        }
        handleChangeViewMode == null ? void 0 : handleChangeViewMode();
        handleResetWip();
      }
    },
    [
      filter,
      filterMultiValues,
      handleChangeViewMode,
      handleMultiValueFilterCommit,
      handleResetWip,
      controller,
      refs.domReference
    ]
  );
  const handleShiftTabInput = useCallback(
    (event, multiValueEdit) => {
      if (event.key === "Tab" && event.shiftKey) {
        if (multiValueEdit) {
          event.preventDefault();
          handleMultiValueFilterCommit(controller, filter, filterMultiValues, true);
        }
        handleChangeViewMode == null ? void 0 : handleChangeViewMode();
        handleResetWip();
      }
    },
    [filter, filterMultiValues, handleChangeViewMode, handleMultiValueFilterCommit, handleResetWip, controller]
  );
  const handleEnterInput = useCallback(
    (event, multiValueEdit) => {
      var _a2;
      if (event.key === "Enter" && activeIndex != null) {
        if (!filteredDropDownItems[activeIndex]) {
          return;
        }
        const selectedItem = filteredDropDownItems[activeIndex];
        if (multiValueEdit) {
          handleLocalMultiValueChange(selectedItem);
          setInputValue("");
        } else {
          const payload = generateFilterUpdatePayload({
            filterInputType,
            item: selectedItem,
            filter,
            setFilterMultiValues,
            onAddCustomValue
          });
          if (filterInputType === "value" && payload.value !== (filter == null ? void 0 : filter.value)) {
            (_a2 = controller.startProfile) == null ? void 0 : _a2.call(controller, FILTER_CHANGED_INTERACTION);
          }
          controller.updateFilter(filter, payload);
          populateInputValueOnInputTypeSwitch({
            populateInputOnEdit,
            item: selectedItem,
            filterInputType,
            setInputValue,
            filter
          });
          switchToNextInputType(
            filterInputType,
            setInputType,
            handleChangeViewMode,
            refs.domReference.current,
            // preventing focus on filter pill only when last filter for better backspace experience
            isLastFilter ? false : void 0
          );
          setActiveIndex(null);
          if (isLastFilter) {
            focusOnWipInputRef == null ? void 0 : focusOnWipInputRef();
          }
        }
      }
    },
    [
      activeIndex,
      filteredDropDownItems,
      handleLocalMultiValueChange,
      controller,
      filter,
      filterInputType,
      populateInputOnEdit,
      handleChangeViewMode,
      refs.domReference,
      isLastFilter,
      focusOnWipInputRef,
      onAddCustomValue
    ]
  );
  const handleEditMultiValuePill = useCallback(
    (value) => {
      var _a2;
      const valueLabel = value.label || value.value;
      setFilterMultiValues((prev) => prev.filter((item) => item.value !== value.value));
      setPreventFiltering(true);
      setInputValue(valueLabel);
      (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();
      setTimeout(() => {
        var _a3;
        (_a3 = refs.domReference.current) == null ? void 0 : _a3.select();
      });
    },
    [refs.domReference]
  );
  useEffect(() => {
    if (open) {
      handleFetchOptions(filterInputType);
    }
  }, [open, filterInputType]);
  useEffect(() => {
    var _a2, _b2, _c2, _d;
    if (!isAlwaysWip) {
      if (hasMultiValueOperator && ((_a2 = filter == null ? void 0 : filter.values) == null ? void 0 : _a2.length)) {
        const multiValueOptions = filter.values.reduce(
          (acc, value, i) => {
            var _a3;
            return [
              ...acc,
              {
                label: ((_a3 = filter.valueLabels) == null ? void 0 : _a3[i]) || value,
                value
              }
            ];
          },
          []
        );
        setFilterMultiValues(multiValueOptions);
      }
      if (!hasMultiValueOperator && populateInputOnEdit) {
        setInputValue((_c2 = (_b2 = filter == null ? void 0 : filter.valueLabels) == null ? void 0 : _b2[0]) != null ? _c2 : (filter == null ? void 0 : filter.value) || "");
        setTimeout(() => {
          var _a3;
          (_a3 = refs.domReference.current) == null ? void 0 : _a3.select();
        });
      }
      (_d = refs.domReference.current) == null ? void 0 : _d.focus();
    }
  }, []);
  useEffect(() => {
    if (isMultiValueEdit && filterMultiValues) {
      setTimeout(() => setForceRefresh({}));
    }
  }, [filterMultiValues, isMultiValueEdit]);
  useLayoutEffect(() => {
    if (filterInputTypeRef.current) {
      filterInputTypeRef.current = filterInputType;
    }
  }, [filterInputType]);
  useLayoutEffect(() => {
    var _a2, _b2;
    if (activeIndex !== null && rowVirtualizer.range && (activeIndex > ((_a2 = rowVirtualizer.range) == null ? void 0 : _a2.endIndex) || activeIndex < ((_b2 = rowVirtualizer.range) == null ? void 0 : _b2.startIndex))) {
      rowVirtualizer.scrollToIndex(activeIndex);
    }
  }, [activeIndex, rowVirtualizer]);
  const keyLabel = (_a = filter == null ? void 0 : filter.keyLabel) != null ? _a : filter == null ? void 0 : filter.key;
  return /* @__PURE__ */ React.createElement("div", { className: styles.comboboxWrapper }, filter ? /* @__PURE__ */ React.createElement("div", { className: styles.pillWrapper }, (filter == null ? void 0 : filter.key) ? /* @__PURE__ */ React.createElement("div", { className: cx(styles.basePill, styles.keyPill) }, keyLabel) : null, (filter == null ? void 0 : filter.key) && (filter == null ? void 0 : filter.operator) && filterInputType !== "operator" ? /* @__PURE__ */ React.createElement(
    "div",
    {
      id: operatorIdentifier,
      className: cx(
        styles.basePill,
        !filter.origin && styles.operatorPill,
        filter.origin && styles.keyPill,
        operatorIdentifier
      ),
      "aria-label": t(
        "grafana-scenes.variables.ad-hoc-combobox.aria-label-edit-filter-operator",
        "Edit filter operator"
      ),
      tabIndex: filter.origin ? -1 : 0,
      onClick: (event) => {
        if (filter.origin) {
          handleChangeViewMode == null ? void 0 : handleChangeViewMode();
          return;
        }
        event.stopPropagation();
        setInputValue("");
        switchInputType("operator", setInputType, void 0, refs.domReference.current);
      },
      onKeyDown: (event) => {
        if (filter.origin) {
          return;
        }
        handleShiftTabInput(event, hasMultiValueOperator);
        if (event.key === "Enter") {
          setInputValue("");
          switchInputType("operator", setInputType, void 0, refs.domReference.current);
        }
      },
      ...!filter.origin && { role: "button" }
    },
    filter.operator
  ) : null, /* @__PURE__ */ React.createElement("div", { ref: multiValuePillWrapperRef }), isMultiValueEdit ? filterMultiValues.map((item, i) => /* @__PURE__ */ React.createElement(
    MultiValuePill,
    {
      key: `${item.value}-${i}`,
      item,
      index: i,
      handleRemoveMultiValue,
      handleEditMultiValuePill
    }
  )) : null) : null, /* @__PURE__ */ React.createElement(
    "input",
    {
      ...getReferenceProps({
        ref: refs.setReference,
        onChange,
        value: inputValue,
        // dynamic placeholder to display operator and/or value in filter edit mode
        placeholder: generatePlaceholder(filter, filterInputType, isMultiValueEdit, isAlwaysWip, inputPlaceholder),
        "aria-autocomplete": "list",
        onKeyDown(event) {
          if (!open) {
            setOpen(true);
            return;
          }
          if (filterInputType === "operator") {
            handleShiftTabInput(event);
          }
          handleBackspaceInput(event, isMultiValueEdit);
          handleTabInput(event, isMultiValueEdit);
          handleEnterInput(event, isMultiValueEdit);
        }
      }),
      className: cx(styles.inputStyle, { [styles.loadingInputPadding]: !optionsLoading }),
      onClick: (event) => {
        event.stopPropagation();
        onInputClick == null ? void 0 : onInputClick();
        setOpen(true);
      },
      onFocus: () => {
        setOpen(true);
      }
    }
  ), optionsLoading ? /* @__PURE__ */ React.createElement(Spinner, { className: styles.loadingIndicator, inline: true }) : null, /* @__PURE__ */ React.createElement(FloatingPortal, null, open && /* @__PURE__ */ React.createElement(FloatingFocusManager, { context, initialFocus: -1, visuallyHiddenDismiss: true, modal: true }, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "div",
    {
      style: {
        ...floatingStyles,
        width: `${optionsError ? ERROR_STATE_DROPDOWN_WIDTH : maxOptionWidth}px`,
        transform: isMultiValueEdit ? `translate(${((_b = multiValuePillWrapperRef.current) == null ? void 0 : _b.getBoundingClientRect().left) || 0}px, ${(((_c = refs.domReference.current) == null ? void 0 : _c.getBoundingClientRect().bottom) || 0) + 10}px )` : floatingStyles.transform
      },
      ref: refs.setFloating,
      className: styles.dropdownWrapper,
      tabIndex: -1
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        style: {
          height: `${rowVirtualizer.getTotalSize() || VIRTUAL_LIST_ITEM_HEIGHT}px`
          // fallback to 38px for loading/error/no options placeholders
        },
        ...getFloatingProps(),
        tabIndex: -1
      },
      optionsLoading ? /* @__PURE__ */ React.createElement(LoadingOptionsPlaceholder, null) : optionsError ? /* @__PURE__ */ React.createElement(OptionsErrorPlaceholder, { handleFetchOptions: () => handleFetchOptions(filterInputType) }) : !filteredDropDownItems.length && (!allowCustomValue || filterInputType === "operator" || !inputValue) ? /* @__PURE__ */ React.createElement(NoOptionsPlaceholder, null) : rowVirtualizer.getVirtualItems().map((virtualItem) => {
        var _a2;
        const item = filteredDropDownItems[virtualItem.index];
        const index = virtualItem.index;
        if (item.options) {
          return /* @__PURE__ */ React.createElement(
            "div",
            {
              key: `${item.label}+${index}`,
              className: cx(styles.optionGroupLabel, styles.groupTopBorder),
              style: {
                height: `${virtualItem.size}px`,
                transform: `translateY(${virtualItem.start}px)`
              }
            },
            /* @__PURE__ */ React.createElement(Text, { weight: "bold", variant: "bodySmall", color: "secondary" }, item.label)
          );
        }
        const nextItem = filteredDropDownItems[virtualItem.index + 1];
        const shouldAddBottomBorder = nextItem && !nextItem.group && !nextItem.options && item.group;
        const itemLabel = (_a2 = item.label) != null ? _a2 : item.value;
        return (
          // key is included in getItemProps()
          // eslint-disable-next-line react/jsx-key
          /* @__PURE__ */ React.createElement(
            DropdownItem,
            {
              ...getItemProps({
                key: `${item.value}-${index}`,
                ref(node) {
                  listRef.current[index] = node;
                },
                onClick(event) {
                  var _a3, _b2;
                  if (filterInputType !== "value") {
                    event.stopPropagation();
                  }
                  if (isMultiValueEdit) {
                    event.preventDefault();
                    event.stopPropagation();
                    handleLocalMultiValueChange(item);
                    setInputValue("");
                    (_a3 = refs.domReference.current) == null ? void 0 : _a3.focus();
                  } else {
                    const payload = generateFilterUpdatePayload({
                      filterInputType,
                      item,
                      filter,
                      setFilterMultiValues,
                      onAddCustomValue
                    });
                    if (filterInputType === "value" && payload.value !== (filter == null ? void 0 : filter.value)) {
                      (_b2 = controller.startProfile) == null ? void 0 : _b2.call(controller, FILTER_CHANGED_INTERACTION);
                    }
                    controller.updateFilter(filter, payload);
                    populateInputValueOnInputTypeSwitch({
                      populateInputOnEdit,
                      item,
                      filterInputType,
                      setInputValue,
                      filter
                    });
                    switchToNextInputType(
                      filterInputType,
                      setInputType,
                      handleChangeViewMode,
                      refs.domReference.current,
                      // explicitly preventing focus on filter pill due to a11y error
                      false
                    );
                  }
                }
              }),
              active: activeIndex === index,
              addGroupBottomBorder: shouldAddBottomBorder,
              style: {
                height: `${virtualItem.size}px`,
                transform: `translateY(${virtualItem.start}px)`
              },
              "aria-setsize": filteredDropDownItems.length,
              "aria-posinset": virtualItem.index + 1,
              isMultiValueEdit,
              checked: filterMultiValues.some((val) => val.value === item.value)
            },
            /* @__PURE__ */ React.createElement("span", null, item.isCustom ? t(
              "grafana-scenes.components.adhoc-filters-combobox.use-custom-value",
              "Use custom value: {{itemLabel}}",
              { itemLabel, interpolation: { escapeValue: false } }
            ) : itemLabel),
            item.description ? /* @__PURE__ */ React.createElement("div", { className: styles.descriptionText }, item.description) : null
          )
        );
      })
    )
  ), isMultiValueEdit && !optionsLoading && !optionsError && filteredDropDownItems.length ? /* @__PURE__ */ React.createElement(
    MultiValueApplyButton,
    {
      onApply: () => {
        handleMultiValueFilterCommit(controller, filter, filterMultiValues);
        handleResetWip();
        handleChangeViewMode == null ? void 0 : handleChangeViewMode();
        setOpen(false);
      },
      floatingElement: refs.floating.current,
      maxOptionWidth,
      menuHeight: Math.min(rowVirtualizer.getTotalSize(), MAX_MENU_HEIGHT)
    }
  ) : null))));
});
const getStyles = (theme) => ({
  comboboxWrapper: css({
    display: "flex",
    flexWrap: "wrap"
  }),
  pillWrapper: css({
    display: "flex",
    alignItems: "center",
    flexWrap: "wrap"
  }),
  basePill: css({
    display: "flex",
    alignItems: "center",
    background: theme.colors.action.disabledBackground,
    border: `1px solid ${theme.colors.border.weak}`,
    padding: theme.spacing(0.125, 1, 0.125, 1),
    color: theme.colors.text.primary,
    overflow: "hidden",
    whiteSpace: "nowrap",
    minHeight: theme.spacing(2.75),
    ...theme.typography.bodySmall,
    cursor: "pointer"
  }),
  keyPill: css({
    fontWeight: theme.typography.fontWeightBold,
    cursor: "default"
  }),
  operatorPill: css({
    "&:hover": {
      background: theme.colors.action.hover
    }
  }),
  dropdownWrapper: css({
    backgroundColor: theme.colors.background.primary,
    color: theme.colors.text.primary,
    boxShadow: theme.shadows.z2,
    overflowY: "auto",
    zIndex: theme.zIndex.portal
  }),
  inputStyle: css({
    paddingBlock: 0,
    "&:focus": {
      outline: "none"
    }
  }),
  loadingIndicator: css({
    color: theme.colors.text.secondary,
    marginLeft: theme.spacing(0.5)
  }),
  loadingInputPadding: css({
    paddingRight: theme.spacing(2.5)
  }),
  optionGroupLabel: css({
    padding: theme.spacing(1),
    position: "absolute",
    top: 0,
    left: 0,
    width: "100%"
  }),
  groupTopBorder: css({
    "&:not(:first-child)": {
      borderTop: `1px solid ${theme.colors.border.weak}`
    }
  }),
  descriptionText: css({
    ...theme.typography.bodySmall,
    color: theme.colors.text.secondary,
    paddingTop: theme.spacing(0.5)
  })
});

export { AdHocCombobox };
//# sourceMappingURL=AdHocFiltersCombobox.js.map
