import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { isWalkIn } from "../utils.js";
import PisellSelectHolder from "../../../plus/selectHolder/index.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { createPortal } from "react-dom";
//#region src/components/booking/utils/selectHolderModal.tsx
let modalState = null;
const allSetStateCallbacks = /* @__PURE__ */ new Set();
let renderingInstanceId = null;
function notifyAllInstances(newState) {
	modalState = newState;
	allSetStateCallbacks.forEach((setState) => {
		setState(newState);
	});
}
/**
* 获取 formDataConfig 和 isMinorAndWaiver
*/
function getFormDataConfig(state) {
	var _state$bookingConfig, _holder$form, _holder$form2;
	let _holder = state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.holder;
	if (!_holder) return {
		formDataConfig: null,
		isMinorAndWaiver: false
	};
	const formDataConfig = _objectSpread2(_objectSpread2(_objectSpread2({}, _holder), _holder === null || _holder === void 0 ? void 0 : _holder.form), {}, {
		options: [],
		form_id: _holder === null || _holder === void 0 || (_holder$form = _holder.form) === null || _holder$form === void 0 ? void 0 : _holder$form.id,
		field: _holder === null || _holder === void 0 || (_holder$form2 = _holder.form) === null || _holder$form2 === void 0 ? void 0 : _holder$form2.form_field,
		relation_type: "appointment_booking",
		form_record: []
	});
	let isMinorAndWaiver = false;
	if ((formDataConfig === null || formDataConfig === void 0 ? void 0 : formDataConfig.form_type) === "minors") {
		var _formDataConfig$form_;
		const detail = formDataConfig === null || formDataConfig === void 0 || (_formDataConfig$form_ = formDataConfig.form_field) === null || _formDataConfig$form_ === void 0 ? void 0 : _formDataConfig$form_.find((item) => item.filed_type === "form_to_form" && item.status === "hide");
		if (detail) {
			var _detail$setting;
			isMinorAndWaiver = detail === null || detail === void 0 || (_detail$setting = detail.setting) === null || _detail$setting === void 0 ? void 0 : _detail$setting.linkedTable;
		}
	}
	return {
		formDataConfig,
		isMinorAndWaiver
	};
}
/**
* 获取 holder 选项列表
*/
function getHolderOptions(state) {
	var _state$pet, _state$bookingConfig2, _state$pet2, _state$pet3;
	const holdersFromState = Array.isArray(state === null || state === void 0 || (_state$pet = state.pet) === null || _state$pet === void 0 ? void 0 : _state$pet.holders) ? state.pet.holders : [];
	const formId = (state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.appointment_subject) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.form_id) || 0;
	const holdersFromValue = Array.isArray(state === null || state === void 0 || (_state$pet2 = state.pet) === null || _state$pet2 === void 0 || (_state$pet2 = _state$pet2.value) === null || _state$pet2 === void 0 ? void 0 : _state$pet2[formId]) ? state === null || state === void 0 || (_state$pet3 = state.pet) === null || _state$pet3 === void 0 || (_state$pet3 = _state$pet3.value) === null || _state$pet3 === void 0 ? void 0 : _state$pet3[formId] : [];
	return (holdersFromState.length > 0 ? holdersFromState : holdersFromValue).map((item) => {
		const id = (item === null || item === void 0 ? void 0 : item.id) || (item === null || item === void 0 ? void 0 : item.form_record_id) || (item === null || item === void 0 ? void 0 : item.value);
		if (id === void 0 || id === null) return null;
		return {
			label: (item === null || item === void 0 ? void 0 : item.main_field) || (item === null || item === void 0 ? void 0 : item.label) || (item === null || item === void 0 ? void 0 : item.name) || locales.getText("pisell-select-holder-please-select"),
			value: id,
			avatar: item === null || item === void 0 ? void 0 : item.avatar,
			subtitle: (item === null || item === void 0 ? void 0 : item.subtitle) || (item === null || item === void 0 ? void 0 : item.second_field) || (item === null || item === void 0 ? void 0 : item.sub_field)
		};
	}).filter(Boolean);
}
/**
* 构建 displayConfig
*/
function buildDisplayConfig(state, holderOptions, maxSelectedCount = 1) {
	var _state$bookingConfig3;
	return {
		direction: "vertical",
		selectType: maxSelectedCount > 1 ? "multiple" : "single",
		showAvatar: true,
		showTitle: true,
		showSubtitle: Boolean(holderOptions.some((option) => option.subtitle)),
		isSkipable: (state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.basic) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.subject_require) === "optional"
	};
}
/**
* SelectHolderModal 组件（单例模式）
* 使用 Portal 在 body 上渲染，确保全局只有一个实例
* 可以在多个地方挂载，但实际只会渲染一个实例
*/
const SelectHolderModal = () => {
	const [localState, setLocalState] = useState(modalState);
	const [container, setContainer] = useState(null);
	const instanceIdRef = useRef(Symbol("SelectHolderModal"));
	const isRenderingInstanceRef = useRef(false);
	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 createPortal(/* @__PURE__ */ React.createElement(SelectHolderModalContent, {
		state,
		dispatch,
		initialValue,
		maxSelectedCount,
		resolve,
		onClose: () => {
			setTimeout(() => {
				notifyAllInstances(null);
			}, 350);
		}
	}), container);
};
/**
* SelectHolderModal 内容组件
*/
const SelectHolderModalContent = ({ state, dispatch, initialValue, maxSelectedCount, resolve, onClose }) => {
	var _stateRef$current2, _stateRef$current3, _holderConfig$form;
	const [open, setOpen] = useState(true);
	const [holderOptions, setHolderOptions] = useState(() => getHolderOptions(state));
	const [selectedValues, setSelectedValues] = 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 };
	useEffect(() => {
		stateRef.current = state;
		setHolderOptions(getHolderOptions(state));
	}, [state]);
	const displayConfig = useMemo(() => {
		var _stateRef$current;
		return buildDisplayConfig(stateRef.current, holderOptions, maxSelectedCount || ((_stateRef$current = stateRef.current) === null || _stateRef$current === void 0 || (_stateRef$current = _stateRef$current.bookingConfig) === null || _stateRef$current === void 0 || (_stateRef$current = _stateRef$current.holder) === null || _stateRef$current === void 0 ? void 0 : _stateRef$current.maxSelectedCount) || 1);
	}, [
		holderOptions,
		maxSelectedCount,
		state
	]);
	const { formDataConfig, isMinorAndWaiver } = useMemo(() => getFormDataConfig(stateRef.current), [(_stateRef$current2 = stateRef.current) === null || _stateRef$current2 === void 0 || (_stateRef$current2 = _stateRef$current2.bookingConfig) === null || _stateRef$current2 === void 0 ? void 0 : _stateRef$current2.holder]);
	const holderConfig = ((_stateRef$current3 = stateRef.current) === null || _stateRef$current3 === void 0 || (_stateRef$current3 = _stateRef$current3.bookingConfig) === null || _stateRef$current3 === void 0 ? void 0 : _stateRef$current3.holder) || {};
	const title = (holderConfig === null || holderConfig === void 0 || (_holderConfig$form = holderConfig.form) === null || _holderConfig$form === void 0 ? void 0 : _holderConfig$form.title) || (holderConfig === null || holderConfig === void 0 ? void 0 : holderConfig.title) || 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) resolve(nextValues.map((val) => Number(val)));
		else resolve(null);
		setTimeout(() => {
			onClose();
		}, 300);
	};
	const handleAdd = () => {
		var _currentState$pet, _currentState$client, _currentState$client2, _currentState$pet$for, _currentState$pet$for2;
		const currentState = stateRef.current;
		const waiverForm = currentState === null || currentState === void 0 || (_currentState$pet = currentState.pet) === null || _currentState$pet === void 0 ? void 0 : _currentState$pet.waiverForm;
		currentState.action({
			type: "pisell1.goCustomFormAddData",
			data: {
				zIndex: 1101,
				customerId: (_currentState$client = currentState.client) === null || _currentState$client === void 0 || (_currentState$client = _currentState$client.value) === null || _currentState$client === void 0 ? void 0 : _currentState$client.id,
				formDataConfig: isMinorAndWaiver ? _objectSpread2(_objectSpread2({}, waiverForm), {}, {
					customer_id: (_currentState$client2 = currentState.client) === null || _currentState$client2 === void 0 || (_currentState$client2 = _currentState$client2.value) === null || _currentState$client2 === void 0 ? void 0 : _currentState$client2.id,
					is_franchisor: (_currentState$pet$for = currentState.pet.formData) === null || _currentState$pet$for === void 0 || (_currentState$pet$for = _currentState$pet$for[0]) === null || _currentState$pet$for === void 0 ? void 0 : _currentState$pet$for.is_franchisor
				}) : _objectSpread2({}, ((_currentState$pet$for2 = currentState.pet.formData) === null || _currentState$pet$for2 === void 0 ? void 0 : _currentState$pet$for2[0]) || {})
			},
			callback: (res) => {
				var _currentState$client3;
				let obj = {};
				for (let item of res) obj[item.key] = item.value;
				const newHolders = !isWalkIn((_currentState$client3 = currentState.client) === null || _currentState$client3 === void 0 || (_currentState$client3 = _currentState$client3.value) === null || _currentState$client3 === void 0 ? void 0 : _currentState$client3.id) ? [obj, ...currentState.pet.holders || []] : currentState.pet.holders || [];
				updateStateHolders(newHolders);
				const updatedState = _objectSpread2(_objectSpread2({}, currentState), {}, { pet: _objectSpread2(_objectSpread2({}, currentState.pet), {}, { holders: newHolders }) });
				stateRef.current = updatedState;
				setHolderOptions(getHolderOptions(updatedState));
			}
		});
	};
	const handleSkip = () => {
		setOpen(false);
		if (resolve) resolve(null);
		setTimeout(() => {
			onClose();
		}, 300);
	};
	return /* @__PURE__ */ React.createElement(PisellSelectHolder, {
		open,
		modalConfig: {
			title: `${locales.getText("pisell-select-holder-please-select")} ${maxSelectedCount || 1} ${title}`,
			confirmText: locales.getText("pisell2.text.confirm")
		},
		dataSource: holderOptions,
		value: selectedValues,
		displayConfig,
		maxSelectedCount,
		allowAdd: true,
		onClose: handleClose,
		onConfirm: handleConfirm,
		onAdd: handleAdd,
		onSkip: handleSkip
	});
};
/**
* 通过 await 调用的 Holder 选择弹窗
* @param options 配置选项
* @returns Promise，resolve 时返回选中的 holder ID 数组，或 null（用户取消时）
*/
function selectHolderModal(options) {
	const { state, dispatch, initialValue, maxSelectedCount } = options;
	return new Promise((resolve) => {
		if (modalState && modalState.resolve) modalState.resolve(null);
		notifyAllInstances({
			open: true,
			state,
			dispatch,
			initialValue,
			maxSelectedCount,
			resolve
		});
	});
}
//#endregion
export { SelectHolderModal, selectHolderModal };
