"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.ReferenceEdit = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _designSystem = require("@wix/design-system");
var _patternsFields = require("@wix/patterns-fields");
var _useCloseOnAncestorScroll = require("../../../../hooks/useCloseOnAncestorScroll");
var _useFilterCollectionStates = require("../../../../hooks/useFilterCollectionStates");
var _providers = require("../../../../providers");
var _getImageFieldId = require("./getImageFieldId");
var _react2 = require("@wix/bex-core/react");
var _mobxReactLite = require("mobx-react-lite");
var _openCollectionContext = require("./openCollectionContext");
var _jsxFileName = "/home/builduser/work/843658b9f44192f0/packages/cairo/dist/cjs/components/EditableTable/cellTypes/reference/Edit.tsx";
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 _ReferenceEditContent({
  value,
  onChange,
  onCommit,
  onCancel,
  typeConfig,
  editTrigger,
  inputRef
}) {
  const config = typeConfig;
  const refSchema = config == null ? void 0 : config.refSchema;
  const acHandle = (0, _react.useRef)(null);
  const wrapperRef = (0, _react.useRef)(null);
  // Opener provided by ReferenceEditWrapper (a stable ancestor) so the
  // navigation + return-to-foreground subscription survive this editor
  // unmounting when the overlay opens.
  const openReferencedCollection = (0, _openCollectionContext.useOpenReferencedCollection)();
  const collection = (0, _react2.useCollection)({
    queryName: `reference-cell-edit-${(refSchema == null ? void 0 : refSchema.id) ?? 'unknown'}`,
    itemKey: item => item.id,
    itemName: item => item.name,
    fetchData: async query => {
      if (!(config != null && config.fetchReferenceItems)) {
        return {
          items: [],
          total: 0
        };
      }
      return config.fetchReferenceItems(query);
    }
  });
  const initialSearchTextRef = (0, _react.useRef)(editTrigger && typeof editTrigger === 'object' && editTrigger.kind === 'type' ? editTrigger.key : undefined);
  // True once the user has typed into the search input. After that, displayValue
  // follows searchValue directly (even when empty) rather than falling back to
  // selectedDisplayValue — prevents the input from snapping back after backspace.
  // useState (not useRef) so that setIsSearchActive(true) triggers a re-render
  // even when collection.search('') produces no MobX change (searchValue already '').
  const [isSearchActive, setIsSearchActive] = (0, _react.useState)(initialSearchTextRef.current !== undefined);
  (0, _react.useEffect)(() => {
    const dispose = collection.init();
    if (initialSearchTextRef.current !== undefined) {
      collection.search(initialSearchTextRef.current, {
        clearResult: true
      });
    }
    return dispose;
  }, [collection]);
  const keyedItems = collection.result.keyedItems;
  const fetchedLastPage = collection.fetchedLastPage;
  const searchValue = collection.query.search.value;
  const idField = (refSchema == null ? void 0 : refSchema.idField) ?? '_id';
  const displayField = (refSchema == null ? void 0 : refSchema.displayField) ?? 'title';
  const imageField = (0, _getImageFieldId.getImageFieldId)(refSchema == null ? void 0 : refSchema.fields);
  const selectedDisplayValue = value ? String(value[displayField] ?? '') : '';
  const displayValue = isSearchActive ? searchValue : searchValue || selectedDisplayValue;
  const selectedImage = (0, _react.useMemo)(() => {
    const selectedId = value == null ? void 0 : value[idField];
    if (!selectedId) {
      return undefined;
    }
    const foundItem = keyedItems.find(ki => ki.key === String(selectedId));
    if (foundItem != null && foundItem.item.image) {
      return foundItem.item.image;
    }
    if (imageField) {
      return value == null ? void 0 : value[imageField];
    }
    return undefined;
  }, [value, idField, keyedItems, imageField]);
  const selectedId = value ? String(value[idField] ?? '') : '';
  const selectedItem = selectedDisplayValue && !searchValue && selectedId && !isSearchActive ? {
    id: selectedId,
    name: selectedDisplayValue,
    image: selectedImage
  } : undefined;
  const items = (0, _react.useMemo)(() => keyedItems.map(ki => ({
    id: String(ki.key),
    name: ki.item.name,
    image: ki.item.image
  })), [keyedItems]);
  const handleSelect = (0, _react.useCallback)(item => {
    onChange({
      [idField]: item.id,
      [displayField]: item.name,
      ...(imageField && item.image ? {
        [imageField]: item.image
      } : {})
    });
    collection.clearSearch();
    onCommit();
  }, [idField, displayField, imageField, onChange, onCommit, collection]);
  const handleChange = (0, _react.useCallback)(e => {
    setIsSearchActive(true);
    if (e.target.value) {
      collection.search(e.target.value, {
        clearResult: true
      });
    } else {
      collection.clearSearch();
    }
  }, [collection]);
  const handleClear = (0, _react.useCallback)(() => {
    onChange(null);
    collection.clearSearch();
    onCommit();
  }, [onChange, onCommit, collection]);
  const handleKeyDown = (0, _react.useCallback)(e => {
    if (e.key === 'Escape') {
      e.preventDefault();
      e.stopPropagation();
      onCancel();
    } else if ((e.key === 'Backspace' || e.key === 'Delete') && value && !displayValue && !isSearchActive) {
      onChange(null);
      collection.clearSearch();
      onCommit();
    }
  }, [onCancel, onChange, onCommit, value, displayValue, collection, isSearchActive]);
  const closeDropdown = (0, _react.useCallback)(() => {
    var _acHandle$current;
    return (_acHandle$current = acHandle.current) == null ? void 0 : _acHandle$current.hideOptions();
  }, []);
  (0, _useCloseOnAncestorScroll.useCloseOnAncestorScroll)(wrapperRef, closeDropdown, true);
  const {
    showInitialLoader,
    fixedFooter
  } = (0, _useFilterCollectionStates.useFilterCollectionStates)({
    collection,
    fixedFooter: config == null || config.renderFooter == null ? void 0 : config.renderFooter()
  });

  // Refresh this editor's dropdown options when the overlay closes — force
  // invalidates the shared query cache (keyed by queryName), so even after this
  // editor has unmounted the next open refetches fresh.
  const handleOpenCollection = (0, _react.useMemo)(() => openReferencedCollection ? () => openReferencedCollection(() => collection.clearResultAndMoveToStart({
    force: true
  })) : undefined, [openReferencedCollection, collection]);
  if (!refSchema) {
    return null;
  }
  return /*#__PURE__*/_react.default.createElement(_designSystem.Box, {
    ref: wrapperRef,
    width: "100%",
    height: "100%",
    __self: this,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 212,
      columnNumber: 5
    }
  }, /*#__PURE__*/_react.default.createElement(_patternsFields.CellReferenceInput, {
    ref: acHandle,
    items: items,
    value: displayValue,
    selectedItem: selectedItem,
    onChange: handleChange,
    onSelect: handleSelect,
    onClear: handleClear,
    onKeyDown: handleKeyDown,
    clearButton: !!displayValue,
    infiniteScroll: true,
    hasMore: !showInitialLoader && !fetchedLastPage,
    loadMore: collection.fetchNextPageIfNeeded,
    fixedFooter: fixedFooter,
    onBlur: onCommit,
    onOpenCollection: handleOpenCollection,
    autoOpen: !!editTrigger,
    inputRef: inputRef,
    __self: this,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 213,
      columnNumber: 7
    }
  }));
}
const ReferenceEditContent = (0, _mobxReactLite.observer)(_ReferenceEditContent);
const ReferenceEdit = props => /*#__PURE__*/_react.default.createElement(_providers.FilterTranslationProvider, {
  __self: void 0,
  __source: {
    fileName: _jsxFileName,
    lineNumber: 239,
    columnNumber: 3
  }
}, /*#__PURE__*/_react.default.createElement(ReferenceEditContent, (0, _extends2.default)({}, props, {
  __self: void 0,
  __source: {
    fileName: _jsxFileName,
    lineNumber: 240,
    columnNumber: 5
  }
})));
exports.ReferenceEdit = ReferenceEdit;
//# sourceMappingURL=Edit.js.map