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_serve = require("../../serve.js");
const require_ExtensionFormTabContent = require("./ExtensionFormTabContent.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let lodash = require("lodash");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
require("./index.less");
//#region src/plus/saasTeamMembers/components/MemberDrawer/index.tsx
const AntdDrawer = _pisell_materials.Drawer;
const AntdButton = _pisell_materials.Button;
const isValueEqual = (a, b) => {
	if (a === "" && b == null || a == null && b === "") return true;
	if (Array.isArray(a) && Array.isArray(b)) return (0, lodash.isEqual)((0, lodash.sortBy)(a), (0, lodash.sortBy)(b));
	return (0, lodash.isEqual)(a, b);
};
const PREFIX = "saas-member-drawer";
const MemberDrawer = ({ visible, mode, currentMember, roleOptions, roles, onClose, onSubmit, loading, getText, getLocaleText, tenantId, mypisellData, locale }) => {
	const [form] = antd.Form.useForm();
	const [activeTab, setActiveTab] = (0, react.useState)("basic");
	const [selectedRoleIds, setSelectedRoleIds] = (0, react.useState)([]);
	const [isEmailRegistered, setIsEmailRegistered] = (0, react.useState)(false);
	const [checkingEmail, setCheckingEmail] = (0, react.useState)(false);
	const [isBasicFormDirty, setIsBasicFormDirty] = (0, react.useState)(false);
	const [iframeDirtyStates, setIframeDirtyStates] = (0, react.useState)({});
	const extensionTabRefs = (0, react.useRef)({});
	const initialValuesRef = (0, react.useRef)(null);
	const [modal, contextHolder] = antd.Modal.useModal();
	const isFormDirty = (0, react.useMemo)(() => {
		const hasIframeDirty = Object.values(iframeDirtyStates).some(Boolean);
		return isBasicFormDirty || hasIframeDirty;
	}, [isBasicFormDirty, iframeDirtyStates]);
	const handleIframeDirtyChange = (0, react.useCallback)((formId, isDirty) => {
		setIframeDirtyStates((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { [formId]: isDirty }));
	}, []);
	const checkFormDirty = (0, react.useCallback)(() => {
		if (!initialValuesRef.current) return;
		const currentValues = form.getFieldsValue();
		const initialValues = initialValuesRef.current;
		for (const field of [
			"nickname",
			"member_id",
			"status",
			"tenant_role_ids",
			"email",
			"password",
			"first_name",
			"last_name",
			"phone"
		]) if (!isValueEqual(currentValues[field], initialValues[field])) {
			setIsBasicFormDirty(true);
			return;
		}
		setIsBasicFormDirty(false);
	}, [form]);
	(0, react.useEffect)(() => {
		if (visible) {
			let values;
			if (mode === "edit" && currentMember) {
				var _currentMember$roles, _currentMember$accoun, _currentMember$accoun2, _currentMember$accoun3, _currentMember$accoun4;
				const roleIds = ((_currentMember$roles = currentMember.roles) === null || _currentMember$roles === void 0 ? void 0 : _currentMember$roles.map((r) => r.id)) || [];
				values = {
					nickname: currentMember.nickname || "",
					member_id: currentMember.member_id || "",
					status: currentMember.status || "active",
					tenant_role_ids: roleIds,
					email: ((_currentMember$accoun = currentMember.account) === null || _currentMember$accoun === void 0 ? void 0 : _currentMember$accoun.email) || "",
					first_name: ((_currentMember$accoun2 = currentMember.account) === null || _currentMember$accoun2 === void 0 ? void 0 : _currentMember$accoun2.first_name) || "",
					last_name: ((_currentMember$accoun3 = currentMember.account) === null || _currentMember$accoun3 === void 0 ? void 0 : _currentMember$accoun3.last_name) || "",
					phone: ((_currentMember$accoun4 = currentMember.account) === null || _currentMember$accoun4 === void 0 ? void 0 : _currentMember$accoun4.phone) || ""
				};
				form.setFieldsValue(values);
				setSelectedRoleIds(roleIds);
				setIsEmailRegistered(false);
			} else {
				values = {
					nickname: "",
					member_id: "",
					status: "active",
					tenant_role_ids: [],
					email: "",
					password: "",
					first_name: "",
					last_name: "",
					phone: ""
				};
				form.resetFields();
				form.setFieldsValue(values);
				setSelectedRoleIds([]);
				setIsEmailRegistered(false);
			}
			initialValuesRef.current = values;
			setIsBasicFormDirty(false);
			setIframeDirtyStates({});
			setActiveTab("basic");
		}
	}, [
		visible,
		mode,
		currentMember,
		form
	]);
	const handleFormValuesChange = (0, react.useCallback)(() => {
		setTimeout(checkFormDirty, 0);
	}, [checkFormDirty]);
	const { run: checkEmail } = (0, ahooks.useDebounceFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (email) {
			if (!email || mode === "edit") {
				setIsEmailRegistered(false);
				setCheckingEmail(false);
				return;
			}
			setCheckingEmail(true);
			try {
				const account = yield require_serve.getAccountByEmail({ filter: JSON.stringify({
					tenant_id: tenantId,
					email
				}) });
				if (account === null || account === void 0 ? void 0 : account.id) {
					const { first_name, last_name, phone } = account;
					form.setFieldsValue({
						first_name,
						last_name,
						phone
					});
					setIsEmailRegistered(true);
				} else setIsEmailRegistered(false);
			} catch (error) {} finally {
				setCheckingEmail(false);
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), { wait: 500 });
	const handleEmailChange = (0, react.useCallback)((e) => {
		const email = e.target.value;
		if (mode === "create") checkEmail(email);
	}, [mode, checkEmail]);
	const selectedRoles = (0, react.useMemo)(() => {
		return roles.filter((role) => selectedRoleIds.includes(role.id));
	}, [roles, selectedRoleIds]);
	const extensionFormIds = (0, react.useMemo)(() => {
		const formIds = /* @__PURE__ */ new Set();
		selectedRoles.forEach((role) => {
			var _role$metadata;
			if ((_role$metadata = role.metadata) === null || _role$metadata === void 0 ? void 0 : _role$metadata.extension_form_id) formIds.add(role.metadata.extension_form_id);
		});
		return Array.from(formIds);
	}, [selectedRoles]);
	const extensionFormRoles = (0, react.useMemo)(() => {
		const formRoles = {};
		selectedRoles.forEach((role) => {
			var _role$metadata2;
			const formId = (_role$metadata2 = role.metadata) === null || _role$metadata2 === void 0 ? void 0 : _role$metadata2.extension_form_id;
			if (formId) {
				if (!formRoles[formId]) formRoles[formId] = [];
				formRoles[formId].push(getLocaleText(role.name));
			}
		});
		return formRoles;
	}, [selectedRoles, getLocaleText]);
	const prevExtensionFormRolesRef = (0, react.useRef)({});
	const prevAccountIdRef = (0, react.useRef)(void 0);
	const { data: relationList, run: runGetRelationList, refresh: refreshRelationList } = (0, ahooks.useRequest)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (!(currentMember === null || currentMember === void 0 ? void 0 : currentMember.id)) return [];
		if (extensionFormIds.length === 0) return [];
		const data = yield require_serve.getRelationRecords({
			relation_type: "tenant_account",
			relation_id: currentMember.id,
			form_id: extensionFormIds
		});
		return Array.isArray(data) ? data : [];
	}), { manual: true });
	(0, react.useEffect)(() => {
		if ((currentMember === null || currentMember === void 0 ? void 0 : currentMember.id) !== prevAccountIdRef.current) {
			prevExtensionFormRolesRef.current = {};
			prevAccountIdRef.current = currentMember === null || currentMember === void 0 ? void 0 : currentMember.id;
		}
	}, [currentMember === null || currentMember === void 0 ? void 0 : currentMember.id]);
	(0, react.useEffect)(() => {
		if (!visible) return;
		if (!(currentMember === null || currentMember === void 0 ? void 0 : currentMember.id)) return;
		const prev = prevExtensionFormRolesRef.current || {};
		const curr = extensionFormRoles || {};
		const normalize = (obj) => {
			const result = {};
			Object.keys(obj).forEach((key) => {
				const k = Number(key);
				result[k] = (0, lodash.sortBy)(obj[k] || []);
			});
			return result;
		};
		if (!(0, lodash.isEqual)(normalize(prev), normalize(curr))) runGetRelationList();
		prevExtensionFormRolesRef.current = curr;
	}, [
		visible,
		currentMember === null || currentMember === void 0 ? void 0 : currentMember.account_id,
		extensionFormRoles,
		runGetRelationList
	]);
	const handleTabChange = (0, react.useCallback)((key) => {
		if (activeTab === "basic" ? isBasicFormDirty : iframeDirtyStates[parseInt(activeTab.replace("extension-", ""))] || false) modal.confirm({
			title: getText("pisell2.saas.team-members.confirm.unsaved-title"),
			content: getText("pisell2.saas.team-members.confirm.unsaved-content"),
			okText: getText("pisell2.saas.team-members.confirm.leave"),
			cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
			onOk: () => {
				if (activeTab === "basic") {
					setIsBasicFormDirty(false);
					if (initialValuesRef.current) form.setFieldsValue(initialValuesRef.current);
				} else {
					var _extensionTabRefs$cur, _extensionTabRefs$cur2;
					const formId = parseInt(activeTab.replace("extension-", ""));
					(_extensionTabRefs$cur = extensionTabRefs.current[formId]) === null || _extensionTabRefs$cur === void 0 || (_extensionTabRefs$cur2 = _extensionTabRefs$cur.reset) === null || _extensionTabRefs$cur2 === void 0 || _extensionTabRefs$cur2.call(_extensionTabRefs$cur);
					setIframeDirtyStates((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { [formId]: false }));
				}
				setActiveTab(key);
			}
		});
		else setActiveTab(key);
	}, [
		activeTab,
		isBasicFormDirty,
		iframeDirtyStates,
		getText,
		form
	]);
	const handleClose = (0, react.useCallback)(() => {
		if (isFormDirty) modal.confirm({
			title: getText("pisell2.saas.team-members.confirm.unsaved-title"),
			content: getText("pisell2.saas.team-members.confirm.unsaved-content"),
			okText: getText("pisell2.saas.team-members.confirm.leave"),
			cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
			onOk: () => {
				setIsBasicFormDirty(false);
				setIframeDirtyStates({});
				onClose();
			}
		});
		else onClose();
	}, [
		isFormDirty,
		onClose,
		getText
	]);
	const handleBasicInfoSubmit = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		try {
			const values = yield form.validateFields();
			yield onSubmit(values);
			setSelectedRoleIds((values === null || values === void 0 ? void 0 : values.tenant_role_ids) || []);
			setIsBasicFormDirty(false);
			initialValuesRef.current = form.getFieldsValue();
		} catch (error) {
			console.error("Form validation failed:", error);
		}
	}), [form, onSubmit]);
	const isFounder = mode === "edit" && (currentMember === null || currentMember === void 0 ? void 0 : currentMember.type) === "founder";
	const renderBasicInfoTab = () => /* @__PURE__ */ react.default.createElement("div", { className: `${PREFIX}_tab-content` }, /* @__PURE__ */ react.default.createElement(antd.Form, {
		form,
		layout: "vertical",
		size: "large",
		onValuesChange: handleFormValuesChange,
		autoComplete: "false"
	}, /* @__PURE__ */ react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText("pisell2.saas.team-members.form.section.team-member-info")), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "nickname",
		label: getText("pisell2.saas.team-members.form.display-name"),
		rules: [{
			required: true,
			message: getText("pisell2.saas.team-members.form.name-required")
		}],
		help: getText("pisell2.saas.team-members.form.name-hint")
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, { placeholder: getText("pisell2.saas.team-members.form.name-placeholder") })), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "member_id",
		label: getText("pisell2.saas.team-members.form.member-id"),
		help: getText("pisell2.saas.team-members.form.member-id-hint")
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, { placeholder: getText("pisell2.saas.team-members.form.member-id-placeholder") })), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "status",
		label: getText("pisell2.saas.team-members.form.status"),
		initialValue: "active",
		rules: [{
			required: true,
			message: getText("pisell2.saas.team-members.form.status-required")
		}]
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Select, { disabled: isFounder }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Select.Option, { value: "active" }, getText("pisell2.saas.team-members.status.active")), /* @__PURE__ */ react.default.createElement(_pisell_materials.Select.Option, { value: "inactive" }, getText("pisell2.saas.team-members.status.inactive")))), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "tenant_role_ids",
		label: getText("pisell2.saas.team-members.form.roles"),
		rules: [{
			required: true,
			message: getText("pisell2.saas.team-members.form.roles-required")
		}],
		extra: isFounder ? /* @__PURE__ */ react.default.createElement(_pisell_materials.Alert, {
			message: getText("pisell2.saas.team-members.founder-notice"),
			type: "info",
			showIcon: true,
			icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
				type: "pisell2-info-circle",
				size: 16,
				color: "#7f8694",
				style: {
					marginTop: 2,
					alignSelf: "flex-start"
				}
			}),
			className: `${PREFIX}_founder-notice`
		}) : getText("pisell2.saas.team-members.form.roles-hint")
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Select, {
		mode: "multiple",
		placeholder: getText("pisell2.saas.team-members.form.roles-placeholder"),
		options: roleOptions
	}))), /* @__PURE__ */ react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText("pisell2.saas.team-members.form.section.account-email-login")), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "email",
		label: getText("pisell2.saas.team-members.form.email"),
		rules: mode === "create" ? [{
			required: true,
			message: getText("pisell2.saas.team-members.form.email-required")
		}, {
			type: "email",
			message: getText("pisell2.saas.team-members.form.email-invalid")
		}] : [],
		extra: mode === "create" && isEmailRegistered && /* @__PURE__ */ react.default.createElement(_pisell_materials.Alert, {
			type: "info",
			showIcon: true,
			icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
				type: "pisell2-info-circle",
				size: 16,
				color: "#7f8694"
			}),
			className: `${PREFIX}_email-registered-alert`,
			message: getText("pisell2.saas.team-members.form.email-registered")
		})
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, {
		placeholder: getText("pisell2.saas.team-members.form.email-placeholder"),
		disabled: mode === "edit",
		onChange: handleEmailChange,
		prefix: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, {
			type: "pisell2-mail-01",
			size: 18,
			color: "#98A2B3"
		})
	})), mode === "create" && !isEmailRegistered && /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "password",
		label: getText("pisell2.saas.team-members.form.password"),
		rules: [{
			required: true,
			message: getText("pisell2.saas.team-members.form.password-required")
		}, {
			pattern: /^\S{6,}$/,
			message: getText("pisell2.saas.team-members.form.password-invalid")
		}]
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input.Password, { placeholder: getText("pisell2.saas.team-members.form.password-placeholder") }))), /* @__PURE__ */ react.default.createElement("div", { className: `${PREFIX}_section` }, /* @__PURE__ */ react.default.createElement("h6", { className: `${PREFIX}_section-header` }, getText("pisell2.saas.team-members.form.section.personal-info")), /* @__PURE__ */ react.default.createElement("div", { style: {
		display: "grid",
		gridTemplateColumns: "1fr 1fr",
		gap: 16
	} }, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "first_name",
		label: getText("pisell2.saas.team-members.form.first-name")
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, {
		placeholder: getText("pisell2.saas.team-members.form.first-name-placeholder"),
		disabled: mode === "edit" || isEmailRegistered
	})), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "last_name",
		label: getText("pisell2.saas.team-members.form.last-name")
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, {
		placeholder: getText("pisell2.saas.team-members.form.last-name-placeholder"),
		disabled: mode === "edit" || isEmailRegistered
	}))), /* @__PURE__ */ react.default.createElement(_pisell_materials.FormItemInput.Phone, {
		type: "tel",
		name: "phone",
		label: getText("pisell2.saas.team-members.form.mobile"),
		disabled: mode === "edit" || isEmailRegistered
	}))));
	const renderExtensionFormTab = (formId) => {
		const tabLabel = (extensionFormRoles[formId] || []).join(" / ");
		return /* @__PURE__ */ react.default.createElement(require_ExtensionFormTabContent.default, {
			ref: (instance) => {
				extensionTabRefs.current[formId] = instance;
			},
			formId,
			domain: (mypisellData === null || mypisellData === void 0 ? void 0 : mypisellData.domain) || "",
			token: (mypisellData === null || mypisellData === void 0 ? void 0 : mypisellData.account_token) || "",
			locale,
			tenantAccountId: currentMember === null || currentMember === void 0 ? void 0 : currentMember.id,
			onDirtyChange: (isDirty) => handleIframeDirtyChange(formId, isDirty),
			onCancel: onClose,
			getText,
			tabLabel,
			prefix: PREFIX,
			relationList: relationList || [],
			refreshRelationList: runGetRelationList
		});
	};
	const tabItems = (0, react.useMemo)(() => {
		const items = [{
			key: "basic",
			label: getText("pisell2.saas.team-members.tab.basic-info"),
			children: renderBasicInfoTab()
		}];
		if (mode === "edit" && selectedRoleIds.length > 0) extensionFormIds.forEach((formId) => {
			const tabLabel = (extensionFormRoles[formId] || []).join(" / ");
			items.push({
				key: `extension-${formId}`,
				label: tabLabel,
				children: renderExtensionFormTab(formId)
			});
		});
		return items;
	}, [
		mode,
		selectedRoleIds,
		extensionFormIds,
		extensionFormRoles,
		isEmailRegistered,
		checkingEmail,
		loading,
		relationList,
		refreshRelationList
	]);
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement(AntdDrawer, {
		title: mode === "create" ? getText("pisell2.saas.team-members.drawer.create-title") : getText("pisell2.saas.team-members.drawer.edit-title"),
		open: visible,
		onClose: handleClose,
		width: 600,
		className: "saas-member-drawer",
		headerStyle: { borderBottom: "2px solid #f0f0f0" },
		destroyOnHidden: true,
		footer: activeTab === "basic" ? /* @__PURE__ */ react.default.createElement("div", { className: `${PREFIX}_footer` }, /* @__PURE__ */ react.default.createElement(AntdButton, {
			onClick: handleClose,
			style: { marginRight: 8 }
		}, getText("pisell2.saas.team-members.drawer.cancel")), /* @__PURE__ */ react.default.createElement(AntdButton, {
			type: "primary",
			onClick: handleBasicInfoSubmit,
			loading,
			disabled: checkingEmail || mode === "edit" && !isBasicFormDirty
		}, getText("pisell2.saas.team-members.drawer.save"))) : false
	}, /* @__PURE__ */ react.default.createElement(antd.Tabs, {
		activeKey: activeTab,
		onChange: handleTabChange,
		items: tabItems,
		className: `${PREFIX}_tabs`
	})), contextHolder);
};
//#endregion
exports.default = MemberDrawer;
