import { t } from '@grafana/i18n';
import { isArray } from 'lodash';
import React, { useMemo, useState, useEffect } from 'react';
import { useTheme2, getSelectStyles, useStyles2, Checkbox, MultiSelect, Select, ToggleAllState } from '@grafana/ui';
import { selectors } from '@grafana/e2e-selectors';
import { cx, css } from '@emotion/css';
import { getOptionSearcher } from './getOptionSearcher.js';
import { sceneGraph } from '../../core/sceneGraph/index.js';
import { VARIABLE_VALUE_CHANGED_INTERACTION } from '../../performance/interactionConstants.js';
import { getVariableControlId } from '../utils.js';

const filterNoOp$2 = () => true;
const filterAll = (v) => v.value !== "$__all";
const determineToggleAllState = (selectedValues, options) => {
  if (selectedValues.length === options.filter(filterAll).length) {
    return ToggleAllState.allSelected;
  } else if (selectedValues.length === 0 || selectedValues.length === 1 && selectedValues[0] && selectedValues[0].value === "$__all") {
    return ToggleAllState.noneSelected;
  } else {
    return ToggleAllState.indeterminate;
  }
};
function toSelectableValue$2(value, label) {
  return {
    value,
    label: label != null ? label : String(value)
  };
}
function VariableValueSelect({ model, state }) {
  const { value, text, key, options, includeAll, isReadOnly, allowCustomValue = true } = state;
  const [inputValue, setInputValue] = useState("");
  const [hasCustomValue, setHasCustomValue] = useState(false);
  const selectValue = toSelectableValue$2(value, String(text));
  const queryController = sceneGraph.getQueryController(model);
  const optionSearcher = useMemo(() => getOptionSearcher(options, includeAll), [options, includeAll]);
  const onInputChange = (value2, { action }) => {
    if (action === "input-change") {
      setInputValue(value2);
      if (model.onSearchChange) {
        model.onSearchChange(value2);
      }
      return value2;
    }
    return value2;
  };
  const filteredOptions = optionSearcher(inputValue);
  const onOpenMenu = () => {
    if (hasCustomValue) {
      setInputValue(String(text));
    }
  };
  const onCloseMenu = () => {
    setInputValue("");
  };
  return /* @__PURE__ */ React.createElement(
    Select,
    {
      id: key,
      inputId: getVariableControlId(model.state.type, key),
      isValidNewOption: (inputValue2) => inputValue2.trim().length > 0,
      placeholder: t("grafana-scenes.variables.variable-value-select.placeholder-select-value", "Select value"),
      width: "auto",
      disabled: isReadOnly,
      value: selectValue,
      inputValue,
      allowCustomValue,
      virtualized: true,
      filterOption: filterNoOp$2,
      tabSelectsValue: false,
      onInputChange,
      onOpenMenu,
      onCloseMenu,
      options: filteredOptions,
      "data-testid": selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownValueLinkTexts(`${value}`),
      onChange: (newValue) => {
        model.changeValueTo(newValue.value, newValue.label, true);
        queryController == null ? void 0 : queryController.startProfile(VARIABLE_VALUE_CHANGED_INTERACTION);
        if (hasCustomValue !== newValue.__isNew__) {
          setHasCustomValue(newValue.__isNew__);
        }
      }
    }
  );
}
function VariableValueSelectMulti({
  model,
  state
}) {
  const {
    value,
    options,
    key,
    maxVisibleValues,
    noValueOnClear,
    includeAll,
    isReadOnly,
    allowCustomValue = true
  } = state;
  const arrayValue = useMemo(() => isArray(value) ? value : [value], [value]);
  const [uncommittedValue, setUncommittedValue] = useState(arrayValue);
  const [inputValue, setInputValue] = useState("");
  const optionSearcher = useMemo(() => getOptionSearcher(options, includeAll), [options, includeAll]);
  useEffect(() => {
    setUncommittedValue(arrayValue);
  }, [arrayValue]);
  const onInputChange = (value2, { action }) => {
    if (action === "input-change") {
      setInputValue(value2);
      if (model.onSearchChange) {
        model.onSearchChange(value2);
      }
      return value2;
    }
    if (action === "input-blur") {
      setInputValue("");
      return "";
    }
    return inputValue;
  };
  const placeholder = options.length > 0 ? "Select value" : "";
  const filteredOptions = optionSearcher(inputValue);
  return /* @__PURE__ */ React.createElement(
    MultiSelect,
    {
      id: key,
      inputId: getVariableControlId(model.state.type, key),
      placeholder,
      width: "auto",
      inputValue,
      disabled: isReadOnly,
      value: uncommittedValue,
      noMultiValueWrap: true,
      maxVisibleValues: maxVisibleValues != null ? maxVisibleValues : 5,
      tabSelectsValue: false,
      virtualized: true,
      allowCustomValue,
      toggleAllOptions: {
        enabled: true,
        optionsFilter: filterAll,
        determineToggleAllState
      },
      options: filteredOptions,
      closeMenuOnSelect: false,
      components: { Option: OptionWithCheckbox },
      isClearable: true,
      hideSelectedOptions: false,
      blurInputOnSelect: false,
      onInputChange,
      onBlur: () => {
        model.changeValueTo(uncommittedValue, void 0, true);
      },
      filterOption: filterNoOp$2,
      "data-testid": selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownValueLinkTexts(`${uncommittedValue}`),
      onChange: (newValue, action) => {
        if (action.action === "clear" && noValueOnClear) {
          model.changeValueTo([], void 0, true);
        }
        setUncommittedValue(newValue.map((x) => x.value));
      }
    }
  );
}
const OptionWithCheckbox = ({
  children,
  data,
  innerProps,
  innerRef,
  isFocused,
  isSelected,
  indeterminate,
  renderOptionLabel
}) => {
  var _a;
  const { onMouseMove, onMouseOver, ...rest } = innerProps;
  const theme = useTheme2();
  const selectStyles = getSelectStyles(theme);
  const optionStyles = useStyles2(getOptionStyles);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: innerRef,
      className: cx(selectStyles.option, isFocused && selectStyles.optionFocused),
      ...rest,
      "data-testid": selectors.components.Select.option,
      title: data.title,
      onClick: void 0,
      onPointerDown: rest.onClick
    },
    /* @__PURE__ */ React.createElement("div", { className: optionStyles.checkbox }, /* @__PURE__ */ React.createElement(Checkbox, { indeterminate, value: isSelected })),
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: selectStyles.optionBody,
        "data-testid": selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownOptionTexts(
          (_a = data.label) != null ? _a : String(data.value)
        )
      },
      /* @__PURE__ */ React.createElement("span", null, children)
    )
  );
};
OptionWithCheckbox.displayName = "SelectMenuOptions";
const getOptionStyles = (theme) => ({
  checkbox: css({
    marginRight: theme.spacing(2)
  })
});
function MultiOrSingleValueSelect({ model }) {
  const state = model.useState();
  if (state.isMulti) {
    return /* @__PURE__ */ React.createElement(VariableValueSelectMulti, { model, state });
  } else {
    return /* @__PURE__ */ React.createElement(VariableValueSelect, { model, state });
  }
}

export { MultiOrSingleValueSelect, OptionWithCheckbox, VariableValueSelect, VariableValueSelectMulti, toSelectableValue$2 as toSelectableValue };
//# sourceMappingURL=VariableValueSelect.js.map
