import { objectWithoutProperties as _objectWithoutProperties, slicedToArray as _slicedToArray, extends as _extends } from '../../../../../_virtual/_rollupPluginBabelHelpers.js';
import React__default, { forwardRef, useRef, useState } from 'react';
import { classes } from '../../Combobox.tokens.js';
import { cx } from '../../../../../utils/index.js';
import { ComboboxChip } from '../ComboboxChip/ComboboxChip.js';
import { StyledComboboxTarget, StyledContent, StyledText, StyledChips, StyledComboboxInput, StyledComboboxInputHelper, StyledLabel, StyledArrow } from './ComboboxTarget.styles.js';
import { useFocusController } from '../../hooks/useFocusController.js';
import { Keys } from '../../hooks/useKeyNavigation.js';

var _excluded = ["values", "search", "label", "placeholder", "opened", "readOnly", "disabled", "enumerationType", "valueType", "size", "closedWithoutChanges", "id", "chipsRefs", "inputRef", "onChange", "onSearch", "onKeyDown"];
var hasChips = classes.hasChips,
  innerLabelUp = classes.innerLabelUp,
  arrowInverse = classes.arrowInverse,
  comboboxTargetArrow = classes.comboboxTargetArrow,
  comboboxTargeText = classes.comboboxTargeText,
  comboboxTargetInput = classes.comboboxTargetInput,
  comboboxTargetLabel = classes.comboboxTargetLabel;

/**
 * Элемент для выпадающего списка
 */
var ComboboxTarget = /*#__PURE__*/forwardRef(function (_ref, ref) {
  var values = _ref.values,
    search = _ref.search,
    label = _ref.label,
    placeholder = _ref.placeholder,
    opened = _ref.opened,
    readOnly = _ref.readOnly,
    disabled = _ref.disabled,
    enumerationType = _ref.enumerationType,
    valueType = _ref.valueType,
    size = _ref.size,
    closedWithoutChanges = _ref.closedWithoutChanges,
    id = _ref.id,
    chipsRefs = _ref.chipsRefs,
    inputRef = _ref.inputRef,
    onChange = _ref.onChange,
    onSearch = _ref.onSearch,
    onKeyDown = _ref.onKeyDown,
    rest = _objectWithoutProperties(_ref, _excluded);
  var contentRef = useRef(null);
  var inputHelperRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    focused = _useState2[0],
    setFocused = _useState2[1];
  var controlledRefs = {
    contentRef: contentRef,
    inputHelperRef: inputHelperRef,
    inputRef: inputRef
  };
  var textContent = values === null || values === void 0 ? void 0 : values.map(function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 2),
      text = _ref3[1];
    return text;
  }).join(', ');
  var hasValue = values === null || values === void 0 ? void 0 : values.some(function (_ref4) {
    var _ref5 = _slicedToArray(_ref4, 1),
      value = _ref5[0];
    return value;
  });
  var isEnumerationComma = enumerationType === 'comma';
  var isExtraSmall = size === 'xs';
  var isInputNotEmpty = hasValue || search;
  var isInputActive = !hasValue && (opened || focused && !readOnly);
  var hasLabel = label && !isExtraSmall && isEnumerationComma;
  var hasOnlyLabel = !placeholder || label;
  var hasNoAnyTip = !placeholder && !label;
  var placeholderValue = !label && !hasValue || isExtraSmall ? placeholder : undefined;
  var withInnerLabelUp = !isExtraSmall && !hasNoAnyTip && hasOnlyLabel && (isInputActive || hasLabel && isInputNotEmpty) ? innerLabelUp : undefined;
  var withArrowInverse = opened ? arrowInverse : undefined;
  var withHasChips = hasValue && enumerationType === 'chip' ? hasChips : undefined;
  var isLabelVisible = !hasValue && !isExtraSmall || hasLabel;
  var isEnumerationVisible = hasValue && valueType !== 'single';
  var onChipClick = function onChipClick(event) {
    return event.stopPropagation();
  };
  var _useFocusController = useFocusController({
      controlledRefs: controlledRefs,
      opened: opened,
      hasValue: hasValue,
      textContent: textContent,
      search: search,
      values: values,
      valueType: valueType,
      readOnly: readOnly,
      closedWithoutChanges: closedWithoutChanges,
      updateFocused: setFocused,
      updateSearch: onSearch,
      onChipClick: onChipClick
    }),
    onClickText = _useFocusController.onClickText,
    onFocusInput = _useFocusController.onFocusInput,
    onBlurInput = _useFocusController.onBlurInput;
  var onChipClear = function onChipClear(value, text, index) {
    var newValue = values === null || values === void 0 ? void 0 : values.filter(function (_ref6) {
      var _ref7 = _slicedToArray(_ref6, 2),
        itemValue = _ref7[0],
        itemText = _ref7[1];
      return !(itemValue === value && itemText === text);
    }).map(function (_ref8) {
      var _ref9 = _slicedToArray(_ref8, 1),
        itemValue = _ref9[0];
      return itemValue;
    });
    chipsRefs === null || chipsRefs === void 0 || chipsRefs.current.splice(index, 1);
    onChange === null || onChange === void 0 || onChange(newValue);
  };
  var onChipKeyDown = function onChipKeyDown(value, text, index, event) {
    var code = event.code;
    if (code === Keys.Tab) {
      event.preventDefault();
    }
    if (code === Keys.Backspace) {
      onChipClear(value, text, index);
    }
  };
  var onKeyDownInput = function onKeyDownInput(event) {
    var _event$currentTarget;
    var code = event.code;
    if (opened && code === Keys.Tab) {
      event.preventDefault();
    }
    if (code === Keys.Backspace && !((_event$currentTarget = event.currentTarget) !== null && _event$currentTarget !== void 0 && _event$currentTarget.value.length)) {
      var newValue = values === null || values === void 0 ? void 0 : values.map(function (_ref10) {
        var _ref11 = _slicedToArray(_ref10, 1),
          itemValue = _ref11[0];
        return itemValue;
      });
      newValue === null || newValue === void 0 || newValue.pop();
      chipsRefs === null || chipsRefs === void 0 || chipsRefs.current.pop();
      onChange === null || onChange === void 0 || onChange(newValue);
    }
  };
  var onChangeInput = function onChangeInput(event) {
    onSearch === null || onSearch === void 0 || onSearch(event.currentTarget.value);
  };
  var onWheel = function onWheel(event) {
    var deltaY = event.deltaY;
    if (contentRef.current) {
      contentRef.current.scrollLeft += Math.round(deltaY);
    }
  };
  var getRef = function getRef(element, index) {
    if (element && chipsRefs && chipsRefs.current) {
      chipsRefs.current[index] = element;
    }
  };

  // INFO: Нужно очищать на каждый ререндер компонента для актуализации состояния рефов
  if (chipsRefs) {
    chipsRefs.current = [];
  }
  return /*#__PURE__*/React__default.createElement(StyledComboboxTarget, _extends({
    ref: ref,
    opened: opened,
    readOnly: readOnly,
    disabled: disabled,
    title: textContent,
    "aria-label": label,
    className: cx(withInnerLabelUp, withHasChips),
    onWheel: onWheel,
    onKeyDown: onKeyDown
  }, rest), /*#__PURE__*/React__default.createElement(StyledContent, {
    tabIndex: -1,
    ref: contentRef,
    className: withHasChips
  }, isEnumerationVisible && (isEnumerationComma ? /*#__PURE__*/React__default.createElement(StyledText, {
    className: comboboxTargeText,
    onClick: onClickText
  }, textContent) : /*#__PURE__*/React__default.createElement(StyledChips, null, values === null || values === void 0 ? void 0 : values.map(function (_ref12, index) {
    var _ref13 = _slicedToArray(_ref12, 2),
      value = _ref13[0],
      text = _ref13[1];
    return /*#__PURE__*/React__default.createElement(ComboboxChip, {
      index: index,
      ref: function ref(element) {
        return getRef(element, index);
      },
      key: "".concat(value, "_").concat(text),
      disabled: disabled,
      readOnly: readOnly,
      value: value,
      text: text,
      onClear: function onClear(v, t) {
        return onChipClear(v, t, index);
      },
      onClick: onChipClick,
      onKeyDown: onChipKeyDown
    });
  }))), /*#__PURE__*/React__default.createElement(StyledComboboxInput, {
    ref: inputRef,
    role: "textbox",
    className: comboboxTargetInput,
    value: search,
    placeholder: placeholderValue,
    disabled: disabled,
    readOnly: readOnly,
    onFocus: onFocusInput,
    onBlur: onBlurInput,
    onChange: onChangeInput,
    onKeyDown: onKeyDownInput
  }), valueType === 'multiple' && /*#__PURE__*/React__default.createElement(StyledComboboxInputHelper, {
    ref: inputHelperRef
  }, search)), isLabelVisible && /*#__PURE__*/React__default.createElement(StyledLabel, {
    className: comboboxTargetLabel,
    htmlFor: id
  }, label), /*#__PURE__*/React__default.createElement(StyledArrow, {
    size: "s",
    className: cx(comboboxTargetArrow, withArrowInverse)
  }));
});

export { ComboboxTarget };
//# sourceMappingURL=ComboboxTarget.js.map
