const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_utils = require("../../../clientName/utils.js");
const require_index = require("../../../../pro/compensatedPisellContainer/index.js");
const require_index$1 = require("../../../clientCard/index.js");
const require_index$2 = require("../../../clinetSearch/index.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
//#region src/plus/saleDetail/components/Client/ClientSelector.tsx
function getErrorMessage(error) {
	if (error instanceof Error) return error.message;
	return String(error || "");
}
function getCustomerId(customer) {
	var _customer$id;
	return (_customer$id = customer === null || customer === void 0 ? void 0 : customer.id) !== null && _customer$id !== void 0 ? _customer$id : customer === null || customer === void 0 ? void 0 : customer.customer_id;
}
function isWalkInCustomer(customer) {
	const id = getCustomerId(customer);
	if (id === void 0 || id === null) return true;
	if (typeof id === "string") return [
		"",
		"0",
		"1"
	].includes(id);
	return [0, 1].includes(id);
}
function normalizeCustomer(customer) {
	if (!customer) return void 0;
	const displayName = customer.display_name || customer.name || [customer.first_name, customer.last_name].filter(Boolean).join(" ");
	return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, customer), {}, {
		customer_id: getCustomerId(customer),
		name: customer.name || displayName,
		display_name: displayName,
		nickname: customer.nickname || displayName
	});
}
function extractContactsInfo(customer) {
	const contactsInfo = customer === null || customer === void 0 ? void 0 : customer.contacts_info;
	if (!contactsInfo) return null;
	return contactsInfo.value || contactsInfo;
}
const ClientSelector = (0, react.forwardRef)(({ className, value, list = [], loading = false, loadingMore = false, resultLoading, hasMore = false, pagination, isShowAvatar, disabledSwitch, disabledSwitchText, clientCardProps, beforeSwitchModalOpen, variant, onSearch, onLoadMore, onChangePage, onSelect, onAddToFirst, onClientChange, resolveContactsInfo, onContactsInfoChange, onOpenCustomerDetail }, ref) => {
	const clientSearchRef = (0, react.useRef)(null);
	const [searchModalVisible, setSearchModalVisible] = (0, react.useState)(false);
	const [switchModalVisible, setSwitchModalVisible] = (0, react.useState)(false);
	const [pendingCustomer, setPendingCustomer] = (0, react.useState)(null);
	const [keyword, setKeyword] = (0, react.useState)("");
	const Toast = (0, _pisell_materials.useToast)();
	const currentVariant = variant || "desktop";
	const isPhoneVariant = currentVariant === "phone";
	const selectedCustomer = value || null;
	const customer = (0, react.useMemo)(() => normalizeCustomer(selectedCustomer), [selectedCustomer]);
	const refreshClientList = (0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (nextKeyword) {
			try {
				var _clientSearchRef$curr, _clientSearchRef$curr2;
				yield onSearch(nextKeyword, { showLoading: false });
				(_clientSearchRef$curr = clientSearchRef.current) === null || _clientSearchRef$curr === void 0 || (_clientSearchRef$curr2 = _clientSearchRef$curr.resetScrollPosition) === null || _clientSearchRef$curr2 === void 0 || _clientSearchRef$curr2.call(_clientSearchRef$curr);
			} catch (error) {
				var _Toast$error;
				console.error("[ClientSelector] refresh customer list failed:", error);
				Toast === null || Toast === void 0 || (_Toast$error = Toast.error) === null || _Toast$error === void 0 || _Toast$error.call(Toast, getErrorMessage(error));
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	const handleSearchClient = (0, ahooks.useMemoizedFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (nextKeyword) {
			try {
				var _clientSearchRef$curr3, _clientSearchRef$curr4;
				yield onSearch(nextKeyword, { showLoading: true });
				(_clientSearchRef$curr3 = clientSearchRef.current) === null || _clientSearchRef$curr3 === void 0 || (_clientSearchRef$curr4 = _clientSearchRef$curr3.resetScrollPosition) === null || _clientSearchRef$curr4 === void 0 || _clientSearchRef$curr4.call(_clientSearchRef$curr3);
			} catch (error) {
				var _Toast$error2;
				console.error("[ClientSelector] search customer failed:", error);
				Toast === null || Toast === void 0 || (_Toast$error2 = Toast.error) === null || _Toast$error2 === void 0 || _Toast$error2.call(Toast, getErrorMessage(error));
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const debouncedSearch = (0, ahooks.useDebounceFn)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (nextKeyword) {
			if (!searchModalVisible) return;
			yield refreshClientList(nextKeyword);
		});
		return function(_x3) {
			return _ref3.apply(this, arguments);
		};
	}(), { wait: 500 });
	(0, react.useEffect)(() => {
		if (searchModalVisible) {
			debouncedSearch.run(keyword);
			return;
		}
		if (keyword) setKeyword("");
	}, [searchModalVisible, keyword]);
	const showDisabledSwitchTip = (0, ahooks.useMemoizedFn)(() => {
		var _Toast$info;
		Toast === null || Toast === void 0 || (_Toast$info = Toast.info) === null || _Toast$info === void 0 || _Toast$info.call(Toast, disabledSwitchText || _pisell_utils.locales.getText("pisell2.checkout.client-card.tip.partially-paid"));
	});
	const openSearchModal = (0, ahooks.useMemoizedFn)(() => {
		if (disabledSwitch) {
			showDisabledSwitchTip();
			return;
		}
		setSearchModalVisible(true);
	});
	const closeSearchModal = (0, ahooks.useMemoizedFn)(() => {
		setSearchModalVisible(false);
	});
	const applySelectedClient = (0, ahooks.useMemoizedFn)(function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (record) {
			const originCustomer = selectedCustomer;
			yield onSelect(record, originCustomer);
			onContactsInfoChange === null || onContactsInfoChange === void 0 || onContactsInfoChange(resolveContactsInfo ? resolveContactsInfo(record) : extractContactsInfo(record));
			onClientChange === null || onClientChange === void 0 || onClientChange(record, originCustomer);
			setSearchModalVisible(false);
		});
		return function(_x4) {
			return _ref4.apply(this, arguments);
		};
	}());
	const handleSetClient = (0, ahooks.useMemoizedFn)(function() {
		var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (record, options) {
			if (disabledSwitch) {
				showDisabledSwitchTip();
				return;
			}
			if (isWalkInCustomer(selectedCustomer)) {
				yield applySelectedClient(record);
				if (record) {
					var _Toast$success;
					Toast === null || Toast === void 0 || (_Toast$success = Toast.success) === null || _Toast$success === void 0 || _Toast$success.call(Toast, _pisell_utils.locales.getText("pisell2.text.add-client-success"));
				}
				return;
			}
			if (String(getCustomerId(selectedCustomer)) === String(getCustomerId(record))) {
				var _Toast$info2;
				if (options === null || options === void 0 ? void 0 : options.sameClientTip) Toast === null || Toast === void 0 || (_Toast$info2 = Toast.info) === null || _Toast$info2 === void 0 || _Toast$info2.call(Toast, options.sameClientTip);
				setSearchModalVisible(false);
				return;
			}
			if (beforeSwitchModalOpen) try {
				if ((yield beforeSwitchModalOpen()) === false) return;
			} catch (error) {
				console.error("[ClientSelector] before switch callback failed:", error);
				return;
			}
			setPendingCustomer(record);
			setSwitchModalVisible(true);
		});
		return function(_x5, _x6) {
			return _ref5.apply(this, arguments);
		};
	}());
	const handleSelectClient = (0, ahooks.useMemoizedFn)((record) => {
		return handleSetClient(record);
	});
	const handleRemoveClient = (0, ahooks.useMemoizedFn)(() => {
		if (disabledSwitch) {
			showDisabledSwitchTip();
			return;
		}
		applySelectedClient(null);
	});
	const handleAddClientSuccess = (0, ahooks.useMemoizedFn)((record, isChecked) => {
		onAddToFirst === null || onAddToFirst === void 0 || onAddToFirst(record);
		if (isChecked) handleSetClient(record);
	});
	const handleConfirmSwitch = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (pendingCustomer) yield applySelectedClient(pendingCustomer);
		setSwitchModalVisible(false);
		setPendingCustomer(null);
	}));
	const handleCancelSwitch = (0, ahooks.useMemoizedFn)(() => {
		setSwitchModalVisible(false);
		setPendingCustomer(null);
	});
	const handleLoadMore = (0, ahooks.useMemoizedFn)(require_asyncToGenerator._asyncToGenerator(function* () {
		try {
			yield onLoadMore === null || onLoadMore === void 0 ? void 0 : onLoadMore();
		} catch (error) {
			var _Toast$error3;
			console.error("[ClientSelector] load more customers failed:", error);
			Toast === null || Toast === void 0 || (_Toast$error3 = Toast.error) === null || _Toast$error3 === void 0 || _Toast$error3.call(Toast, getErrorMessage(error));
		}
	}));
	const handleChangePage = (0, ahooks.useMemoizedFn)(function() {
		var _ref6 = require_asyncToGenerator._asyncToGenerator(function* (nextPagination) {
			try {
				yield onChangePage === null || onChangePage === void 0 ? void 0 : onChangePage(nextPagination.current, nextPagination.pageSize);
			} catch (error) {
				var _Toast$error4;
				console.error("[ClientSelector] change customer page failed:", error);
				Toast === null || Toast === void 0 || (_Toast$error4 = Toast.error) === null || _Toast$error4 === void 0 || _Toast$error4.call(Toast, getErrorMessage(error));
			}
		});
		return function(_x7) {
			return _ref6.apply(this, arguments);
		};
	}());
	const handleViewClient = (0, ahooks.useMemoizedFn)((record) => {
		if (!onOpenCustomerDetail || !getCustomerId(record)) return;
		const originContactsInfo = record.contacts_info || null;
		onOpenCustomerDetail(record, (detail) => {
			const nextContactsInfo = (detail === null || detail === void 0 ? void 0 : detail.contacts_info) || null;
			const displayName = (detail === null || detail === void 0 ? void 0 : detail.display_name) || record.display_name || "";
			const nextCustomer = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, record), {}, {
				display_name: displayName,
				name: (detail === null || detail === void 0 ? void 0 : detail.name) || record.name || displayName,
				email: (detail === null || detail === void 0 ? void 0 : detail.email) || "",
				phone: (detail === null || detail === void 0 ? void 0 : detail.phone) || "",
				nickname: (detail === null || detail === void 0 ? void 0 : detail.nickname) || displayName,
				country_calling_code: (detail === null || detail === void 0 ? void 0 : detail.country_calling_code) || "",
				first_name: (detail === null || detail === void 0 ? void 0 : detail.first_name) || "",
				last_name: (detail === null || detail === void 0 ? void 0 : detail.last_name) || "",
				contacts_info: nextContactsInfo
			});
			onSelect(nextCustomer, selectedCustomer);
			onClientChange === null || onClientChange === void 0 || onClientChange(nextCustomer, selectedCustomer);
			if (JSON.stringify(originContactsInfo) !== JSON.stringify(nextContactsInfo)) onContactsInfoChange === null || onContactsInfoChange === void 0 || onContactsInfoChange(nextContactsInfo);
			handleSearchClient("");
		});
	});
	const defaultDropdownProps = (0, react.useMemo)(() => ({ buttonProps: {
		icon: /* @__PURE__ */ react.default.createElement("span", { className: "pisell-sale-detail-client__switch-icon" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Iconfont, {
			type: "pisell2-switch-horizontal-01",
			size: 24
		})),
		size: "default",
		onClick: () => {}
	} }), []);
	const resultProps = (0, react.useMemo)(() => ({
		loading,
		onChange: handleChangePage,
		pagination: {
			pageSize: (pagination === null || pagination === void 0 ? void 0 : pagination.pageSize) || 20,
			current: (pagination === null || pagination === void 0 ? void 0 : pagination.page) || 1,
			total: (pagination === null || pagination === void 0 ? void 0 : pagination.total) || 0,
			size: "default",
			showSizeChanger: false
		}
	}), [
		loading,
		pagination,
		handleChangePage
	]);
	(0, react.useImperativeHandle)(ref, () => ({ handleSetClient }));
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("section", { className: (0, classnames.default)("pisell-sale-detail-client", `pisell-sale-detail-client--${currentVariant}`, className) }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-client__line" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-sale-detail-client__card-wrap" }, /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		dataSource: customer,
		onAddClient: openSearchModal,
		onChangeClient: openSearchModal,
		onRemoveClient: handleRemoveClient,
		onViewClient: handleViewClient,
		style: require_objectSpread2._objectSpread2({
			border: "solid",
			borderColor: "#D0D5DD",
			borderWidth: "1px",
			display: "flex",
			boxSizing: "border-box",
			height: "auto"
		}, (clientCardProps === null || clientCardProps === void 0 ? void 0 : clientCardProps.style) || {}),
		isShowAvatar: Boolean(isShowAvatar),
		dropdown: (clientCardProps === null || clientCardProps === void 0 ? void 0 : clientCardProps.dropdown) || defaultDropdownProps,
		avatar: require_objectSpread2._objectSpread2({
			size: "lg",
			useTextAvatar: true
		}, (clientCardProps === null || clientCardProps === void 0 ? void 0 : clientCardProps.avatar) || {}),
		tag: clientCardProps === null || clientCardProps === void 0 ? void 0 : clientCardProps.tag,
		tags: clientCardProps === null || clientCardProps === void 0 ? void 0 : clientCardProps.tags
	})))), /* @__PURE__ */ react.default.createElement(require_index$2.default, {
		ref: clientSearchRef,
		loading,
		dataSource: list,
		onSearch: handleSearchClient,
		keyword,
		onKeywordChange: setKeyword,
		onRowClick: handleSelectClient,
		containerProps: {
			open: searchModalVisible,
			onCancel: closeSearchModal,
			destroyOnClose: true,
			width: 880
		},
		isShowNewButton: false,
		resultProps,
		onAddClient: handleAddClientSuccess,
		onLoadMore: handleLoadMore,
		hasMore,
		resultLoading: resultLoading !== null && resultLoading !== void 0 ? resultLoading : loadingMore
	}), /* @__PURE__ */ react.default.createElement(require_index.default, {
		renderType: isPhoneVariant ? "drawer" : "modal",
		showHandlerBar: isPhoneVariant,
		props: isPhoneVariant ? {
			className: "cart-client-card_switch-modal",
			open: switchModalVisible,
			placement: "bottom",
			width: "100%",
			height: "auto",
			onClose: handleCancelSwitch,
			closable: false,
			title: null,
			destroyOnClose: true,
			bodyStyle: { padding: 0 },
			footer: /* @__PURE__ */ react.default.createElement("div", { style: {
				display: "flex",
				gap: 12,
				paddingBottom: "calc(12px + env(safe-area-inset-bottom))"
			} }, /* @__PURE__ */ react.default.createElement(antd.Button, {
				style: { flex: 1 },
				onClick: handleCancelSwitch
			}, _pisell_utils.locales.getText("pisell2.text.cancel")), /* @__PURE__ */ react.default.createElement(antd.Button, {
				style: { flex: 1 },
				type: "primary",
				onClick: handleConfirmSwitch
			}, _pisell_utils.locales.getText("pisell2.text.switch-account")))
		} : {
			className: "cart-client-card_switch-modal",
			open: switchModalVisible,
			okText: _pisell_utils.locales.getText("pisell2.text.switch-account"),
			cancelText: _pisell_utils.locales.getText("pisell2.text.cancel"),
			onOk: handleConfirmSwitch,
			onCancel: handleCancelSwitch,
			closable: false,
			header: null,
			footerDivider: false,
			destroyOnClose: true
		}
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		textAlign: "center",
		fontWeight: 600,
		padding: variant === "phone" ? "16px 0" : "16px 0 0"
	} }, _pisell_utils.locales.getText("pisell2.text.cart-client-card")(require_utils.getClientName(pendingCustomer)))));
});
ClientSelector.displayName = "ClientSelector";
//#endregion
exports.ClientSelector = ClientSelector;
