var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/booking/utils/selectHolderModal.tsx
var selectHolderModal_exports = {};
__export(selectHolderModal_exports, {
  SelectHolderModal: () => SelectHolderModal,
  selectHolderModal: () => selectHolderModal
});
module.exports = __toCommonJS(selectHolderModal_exports);
var import_react = __toESM(require("react"));
var import_react_dom = require("react-dom");
var import_utils = require("@pisell/utils");
var import_utils2 = require("../utils");
var import_selectHolder = __toESM(require("../../../plus/selectHolder"));
var modalState = null;
var allSetStateCallbacks = /* @__PURE__ */ new Set();
var renderingInstanceId = null;
function notifyAllInstances(newState) {
  modalState = newState;
  allSetStateCallbacks.forEach((setState) => {
    setState(newState);
  });
}
function getFormDataConfig(state) {
  var _a, _b, _c, _d, _e;
  let _holder = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.holder;
  if (!_holder) {
    return { formDataConfig: null, isMinorAndWaiver: false };
  }
  const formDataConfig = {
    ..._holder,
    ..._holder == null ? void 0 : _holder.form,
    options: [],
    form_id: (_b = _holder == null ? void 0 : _holder.form) == null ? void 0 : _b.id,
    field: (_c = _holder == null ? void 0 : _holder.form) == null ? void 0 : _c.form_field,
    relation_type: "appointment_booking",
    form_record: []
  };
  let isMinorAndWaiver = false;
  if ((formDataConfig == null ? void 0 : formDataConfig.form_type) === "minors") {
    const detail = (_d = formDataConfig == null ? void 0 : formDataConfig.form_field) == null ? void 0 : _d.find(
      (item) => item.filed_type === "form_to_form" && item.status === "hide"
    );
    if (detail) {
      isMinorAndWaiver = (_e = detail == null ? void 0 : detail.setting) == null ? void 0 : _e.linkedTable;
    }
  }
  return { formDataConfig, isMinorAndWaiver };
}
function getHolderOptions(state) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  const holdersFromState = Array.isArray((_a = state == null ? void 0 : state.pet) == null ? void 0 : _a.holders) ? state.pet.holders : [];
  const formId = ((_e = (_d = (_c = (_b = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _b.config) == null ? void 0 : _c.basic) == null ? void 0 : _d.appointment_subject) == null ? void 0 : _e.form_id) || 0;
  const holdersFromValue = Array.isArray((_g = (_f = state == null ? void 0 : state.pet) == null ? void 0 : _f.value) == null ? void 0 : _g[formId]) ? (_i = (_h = state == null ? void 0 : state.pet) == null ? void 0 : _h.value) == null ? void 0 : _i[formId] : [];
  const rawList = holdersFromState.length > 0 ? holdersFromState : holdersFromValue;
  return rawList.map((item) => {
    const id = (item == null ? void 0 : item.id) || (item == null ? void 0 : item.form_record_id) || (item == null ? void 0 : item.value);
    if (id === void 0 || id === null) return null;
    return {
      label: (item == null ? void 0 : item.main_field) || (item == null ? void 0 : item.label) || (item == null ? void 0 : item.name) || import_utils.locales.getText("pisell-select-holder-please-select"),
      value: id,
      avatar: item == null ? void 0 : item.avatar,
      subtitle: (item == null ? void 0 : item.subtitle) || (item == null ? void 0 : item.second_field) || (item == null ? void 0 : item.sub_field)
    };
  }).filter(Boolean);
}
function buildDisplayConfig(state, holderOptions, maxSelectedCount = 1) {
  var _a, _b, _c;
  const selectType = maxSelectedCount > 1 ? "multiple" : "single";
  return {
    direction: "vertical",
    selectType,
    showAvatar: true,
    showTitle: true,
    showSubtitle: Boolean(holderOptions.some((option) => option.subtitle)),
    isSkipable: ((_c = (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.subject_require) === "optional"
  };
}
var SelectHolderModal = () => {
  const [localState, setLocalState] = (0, import_react.useState)(modalState);
  const [container, setContainer] = (0, import_react.useState)(null);
  const instanceIdRef = (0, import_react.useRef)(Symbol("SelectHolderModal"));
  const isRenderingInstanceRef = (0, import_react.useRef)(false);
  (0, import_react.useEffect)(() => {
    let containerElement = document.getElementById("select-holder-modal-container");
    if (!containerElement) {
      containerElement = document.createElement("div");
      containerElement.id = "select-holder-modal-container";
      document.body.appendChild(containerElement);
    }
    setContainer(containerElement);
    if (renderingInstanceId === null) {
      renderingInstanceId = instanceIdRef.current;
      isRenderingInstanceRef.current = true;
    } else {
      isRenderingInstanceRef.current = renderingInstanceId === instanceIdRef.current;
    }
    allSetStateCallbacks.add(setLocalState);
    if (modalState && modalState !== localState) {
      setLocalState(modalState);
    }
    return () => {
      allSetStateCallbacks.delete(setLocalState);
      if (isRenderingInstanceRef.current) {
        renderingInstanceId = null;
      }
    };
  }, []);
  if (!localState || !localState.open || !container) {
    return null;
  }
  if (!isRenderingInstanceRef.current) {
    return null;
  }
  const { state, dispatch, initialValue, maxSelectedCount, resolve } = localState;
  return (0, import_react_dom.createPortal)(
    /* @__PURE__ */ import_react.default.createElement(
      SelectHolderModalContent,
      {
        state,
        dispatch,
        initialValue,
        maxSelectedCount,
        resolve,
        onClose: () => {
          setTimeout(() => {
            notifyAllInstances(null);
          }, 350);
        }
      }
    ),
    container
  );
};
var SelectHolderModalContent = ({ state, dispatch, initialValue, maxSelectedCount, resolve, onClose }) => {
  var _a, _b, _c, _d, _e;
  const [open, setOpen] = (0, import_react.useState)(true);
  const [holderOptions, setHolderOptions] = (0, import_react.useState)(
    () => getHolderOptions(state)
  );
  const [selectedValues, setSelectedValues] = (0, import_react.useState)(() => {
    if (Array.isArray(initialValue)) {
      return initialValue.filter(
        (item) => item !== void 0 && item !== null
      );
    }
    if (initialValue === void 0 || initialValue === null || initialValue === "") {
      return [];
    }
    return [initialValue];
  });
  const stateRef = { current: state };
  (0, import_react.useEffect)(() => {
    stateRef.current = state;
    const newOptions = getHolderOptions(state);
    setHolderOptions(newOptions);
  }, [state]);
  const displayConfig = (0, import_react.useMemo)(
    () => {
      var _a2, _b2, _c2;
      return buildDisplayConfig(
        stateRef.current,
        holderOptions,
        maxSelectedCount || ((_c2 = (_b2 = (_a2 = stateRef.current) == null ? void 0 : _a2.bookingConfig) == null ? void 0 : _b2.holder) == null ? void 0 : _c2.maxSelectedCount) || 1
      );
    },
    [holderOptions, maxSelectedCount, state]
  );
  const { formDataConfig, isMinorAndWaiver } = (0, import_react.useMemo)(
    () => getFormDataConfig(stateRef.current),
    [(_b = (_a = stateRef.current) == null ? void 0 : _a.bookingConfig) == null ? void 0 : _b.holder]
  );
  const holderConfig = ((_d = (_c = stateRef.current) == null ? void 0 : _c.bookingConfig) == null ? void 0 : _d.holder) || {};
  const title = ((_e = holderConfig == null ? void 0 : holderConfig.form) == null ? void 0 : _e.title) || (holderConfig == null ? void 0 : holderConfig.title) || import_utils.locales.getText("pisell2.text.holder");
  const updateStateHolders = (holders) => {
    dispatch({
      type: "setPet",
      payload: {
        holders
      }
    });
  };
  const handleClose = () => {
    setOpen(false);
    if (resolve) {
      resolve(null);
    }
    setTimeout(() => {
      onClose();
    }, 300);
  };
  const handleConfirm = (nextValues) => {
    setOpen(false);
    if (resolve) {
      if (nextValues && nextValues.length > 0) {
        const selectedIds = nextValues.map((val) => Number(val));
        resolve(selectedIds);
      } else {
        resolve(null);
      }
    }
    setTimeout(() => {
      onClose();
    }, 300);
  };
  const handleAdd = () => {
    var _a2, _b2, _c2, _d2, _e2, _f, _g, _h;
    const currentState = stateRef.current;
    const waiverForm = (_a2 = currentState == null ? void 0 : currentState.pet) == null ? void 0 : _a2.waiverForm;
    currentState.action({
      type: "pisell1.goCustomFormAddData",
      data: {
        zIndex: 1101,
        customerId: (_c2 = (_b2 = currentState.client) == null ? void 0 : _b2.value) == null ? void 0 : _c2.id,
        formDataConfig: isMinorAndWaiver ? {
          ...waiverForm,
          customer_id: (_e2 = (_d2 = currentState.client) == null ? void 0 : _d2.value) == null ? void 0 : _e2.id,
          is_franchisor: (_g = (_f = currentState.pet.formData) == null ? void 0 : _f[0]) == null ? void 0 : _g.is_franchisor
        } : { ...((_h = currentState.pet.formData) == null ? void 0 : _h[0]) || {} }
      },
      callback: (res) => {
        var _a3, _b3;
        let obj = {};
        for (let item of res) {
          obj[item.key] = item.value;
        }
        const isWalkInBol = (0, import_utils2.isWalkIn)((_b3 = (_a3 = currentState.client) == null ? void 0 : _a3.value) == null ? void 0 : _b3.id);
        const newHolders = !isWalkInBol ? [obj, ...currentState.pet.holders || []] : currentState.pet.holders || [];
        updateStateHolders(newHolders);
        const updatedState = {
          ...currentState,
          pet: {
            ...currentState.pet,
            holders: newHolders
          }
        };
        stateRef.current = updatedState;
        const newOptions = getHolderOptions(updatedState);
        setHolderOptions(newOptions);
      }
    });
  };
  const handleSkip = () => {
    setOpen(false);
    if (resolve) {
      resolve(null);
    }
    setTimeout(() => {
      onClose();
    }, 300);
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_selectHolder.default,
    {
      open,
      modalConfig: {
        title: `${import_utils.locales.getText("pisell-select-holder-please-select")} ${maxSelectedCount || 1} ${title}`,
        confirmText: import_utils.locales.getText("pisell2.text.confirm")
      },
      dataSource: holderOptions,
      value: selectedValues,
      displayConfig,
      maxSelectedCount,
      allowAdd: true,
      onClose: handleClose,
      onConfirm: handleConfirm,
      onAdd: handleAdd,
      onSkip: handleSkip
    }
  );
};
function selectHolderModal(options) {
  const { state, dispatch, initialValue, maxSelectedCount } = options;
  return new Promise((resolve) => {
    if (modalState && modalState.resolve) {
      modalState.resolve(null);
    }
    const newState = {
      open: true,
      state,
      dispatch,
      initialValue,
      maxSelectedCount,
      resolve
    };
    notifyAllInstances(newState);
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SelectHolderModal,
  selectHolderModal
});
