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_objectWithoutProperties = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_index = require("../../utils/index.js");
const require_locales = require("./locales.js");
const require_serve = require("./serve.js");
const require_index$1 = require("./components/MemberDrawer/index.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
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");
let _ant_design_icons = require("@ant-design/icons");
require("./index.less");
//#region src/plus/saasTeamMembers/index.tsx
const _excluded = ["email", "password"];
const SaasTeamMembers = ({ className, style }) => {
	var _context$appHelper, _context$engine, _membersRequest$data, _membersRequest$data2;
	const [searchText, setSearchText] = (0, react.useState)("");
	const [filters, setFilters] = (0, react.useState)({});
	const [drawerVisible, setDrawerVisible] = (0, react.useState)(false);
	const [drawerMode, setDrawerMode] = (0, react.useState)("create");
	const [currentMember, setCurrentMember] = (0, react.useState)(null);
	const [currentPage, setCurrentPage] = (0, react.useState)(1);
	const [pageSize, setPageSize] = (0, react.useState)(10);
	const [modal, contextHolder] = antd.Modal.useModal();
	const context = require_useEngineContext.default();
	const utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	if (utils === null || utils === void 0 ? void 0 : utils.request) require_index.request.setRequest(utils.request);
	const _locale = (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en";
	_pisell_utils.locales.init(require_locales.default, _locale);
	const getText = _pisell_utils.locales.getText;
	const getLocaleText = (0, react.useCallback)((text) => {
		var _context$appHelper2;
		if (!text) return "";
		if (typeof text === "string") return text;
		const { translation } = (context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {};
		return translation(text);
	}, [context]);
	const { tenantId, mypisellData } = (0, react.useMemo)(() => {
		var _utils$store, _utils$store$getState, _core$tenant;
		const core = (_utils$store = utils.store) === null || _utils$store === void 0 || (_utils$store$getState = _utils$store.getState) === null || _utils$store$getState === void 0 || (_utils$store$getState = _utils$store$getState.call(_utils$store)) === null || _utils$store$getState === void 0 || (_utils$store$getState = _utils$store$getState.core) === null || _utils$store$getState === void 0 ? void 0 : _utils$store$getState.core;
		return {
			tenantId: core === null || core === void 0 || (_core$tenant = core.tenant) === null || _core$tenant === void 0 ? void 0 : _core$tenant.tenant_id,
			mypisellData: core === null || core === void 0 ? void 0 : core.mypisell_data
		};
	}, [utils.store]);
	const membersRequest = (0, ahooks.useRequest)(() => {
		const params = {
			page: currentPage,
			size: pageSize,
			with: ["account", "roles"]
		};
		if (searchText) params.search = searchText;
		if (filters.roles && filters.roles.length > 0) params.tenant_role_ids = filters.roles;
		if (filters.status) params.status = filters.status;
		return require_serve.getTeamMembers(params);
	}, { refreshDeps: [
		currentPage,
		pageSize,
		searchText,
		filters
	] });
	const rolesRequest = (0, ahooks.useRequest)(require_serve.getRoles);
	const createRequest = (0, ahooks.useRequest)(require_serve.createTeamMember, {
		manual: true,
		onSuccess: () => {
			setDrawerVisible(false);
			membersRequest.refresh();
		}
	});
	const updateRequest = (0, ahooks.useRequest)((id, data) => require_serve.updateTeamMember(id, data), {
		manual: true,
		onSuccess: () => {
			setDrawerVisible(false);
			membersRequest.refresh();
		}
	});
	const deleteRequest = (0, ahooks.useRequest)(require_serve.deleteTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const activateRequest = (0, ahooks.useRequest)(require_serve.activateTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const deactivateRequest = (0, ahooks.useRequest)(require_serve.deactivateTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const handleAddMember = (0, react.useCallback)(() => {
		setDrawerMode("create");
		setCurrentMember(null);
		setDrawerVisible(true);
	}, []);
	const handleEditMember = (0, react.useCallback)((member) => {
		setDrawerMode("edit");
		setCurrentMember(member);
		setDrawerVisible(true);
	}, []);
	const handleDeleteMember = (0, react.useCallback)((member) => {
		if (member.type === "founder") {
			_pisell_materials.message.error(getText("pisell2.saas.team-members.confirm.founder-restriction"));
			return;
		}
		modal.confirm({
			title: getText("pisell2.saas.team-members.confirm.delete-title"),
			content: getText("pisell2.saas.team-members.confirm.delete-content").replace("{name}", member.nickname),
			okText: getText("pisell2.saas.team-members.delete"),
			cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
			okButtonProps: { danger: true },
			onOk: function() {
				var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
					yield deleteRequest.runAsync(member.id);
				});
				return function onOk() {
					return _ref.apply(this, arguments);
				};
			}()
		});
	}, [getText, deleteRequest]);
	const handleToggleStatus = (0, react.useCallback)((member) => {
		if (member.type === "founder" && member.status === "active") {
			_pisell_materials.message.error(getText("pisell2.saas.team-members.confirm.founder-restriction"));
			return;
		}
		if (member.status === "active") modal.confirm({
			title: getText("pisell2.saas.team-members.confirm.deactivate-title"),
			content: getText("pisell2.saas.team-members.confirm.deactivate-content").replace("{name}", member.nickname),
			okText: getText("pisell2.saas.team-members.deactivate"),
			cancelText: getText("pisell2.saas.team-members.drawer.cancel"),
			onOk: function() {
				var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
					yield deactivateRequest.runAsync(member.id);
				});
				return function onOk() {
					return _ref2.apply(this, arguments);
				};
			}()
		});
		else activateRequest.run(member.id);
	}, [
		getText,
		activateRequest,
		deactivateRequest
	]);
	const handleSubmit = (0, react.useCallback)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (values) {
			if (drawerMode === "create") yield createRequest.runAsync(values);
			else if (currentMember) {
				const { email, password } = values, updateData = require_objectWithoutProperties._objectWithoutProperties(values, _excluded);
				yield updateRequest.runAsync(currentMember.id, updateData);
			}
		});
		return function(_x) {
			return _ref3.apply(this, arguments);
		};
	}(), [
		drawerMode,
		currentMember,
		createRequest,
		updateRequest
	]);
	const handleDrawerClose = (0, react.useCallback)(() => {
		setDrawerVisible(false);
		setCurrentMember(null);
	}, []);
	const columns = (0, react.useMemo)(() => [
		{
			title: getText("pisell2.saas.team-members.column.display-name"),
			dataIndex: "nickname",
			key: "nickname",
			fixed: "left",
			width: 220,
			render: (text, record) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, null, /* @__PURE__ */ react.default.createElement("span", null, text), record.type === "founder" && /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, { color: "blue" }, getText("pisell2.saas.team-members.badge.owner")))
		},
		{
			title: getText("pisell2.saas.team-members.column.member-id"),
			dataIndex: "member_id",
			key: "member_id",
			width: 100,
			render: (text) => text || "-"
		},
		{
			title: getText("pisell2.saas.team-members.column.email"),
			dataIndex: ["account", "email"],
			key: "email",
			render: (text) => text || "-"
		},
		{
			title: getText("pisell2.saas.team-members.column.phone"),
			dataIndex: ["account", "phone"],
			key: "phone",
			width: 180,
			render: (text) => text || "-"
		},
		{
			width: 200,
			title: getText("pisell2.saas.team-members.column.roles"),
			dataIndex: "roles",
			key: "roles",
			render: (roles) => {
				if (!roles || roles.length === 0) return "-";
				const displayRoles = roles.slice(0, 3);
				const remainingCount = roles.length - 3;
				return /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, {
					size: 4,
					wrap: true
				}, displayRoles.map((role) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, { key: role.id }, getLocaleText(role.name))), remainingCount > 0 && /* @__PURE__ */ react.default.createElement(_pisell_materials.Popover, { content: /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, {
					size: 4,
					wrap: true
				}, roles.map((role) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, { key: role.id }, getLocaleText(role.name)))) }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, null, getText("pisell2.saas.team-members.more-roles").replace("{count}", String(remainingCount)))));
			}
		},
		{
			title: getText("pisell2.saas.team-members.column.status"),
			dataIndex: "status",
			key: "status",
			width: 80,
			render: (status) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, {
				variant: "solid",
				color: status === "active" ? "green" : "default"
			}, getText(`pisell2.saas.team-members.status.${status}`))
		},
		{
			title: getText("pisell2.saas.team-members.column.joined-date"),
			dataIndex: "created_at",
			key: "created_at",
			width: 120,
			render: (date) => (0, dayjs.default)(date).format("DD/MM/YYYY")
		},
		{
			title: getText("pisell2.saas.team-members.column.actions"),
			key: "actions",
			width: 120,
			fixed: "right",
			render: (_, record) => {
				const items = [{
					key: "toggle-status",
					label: record.status === "active" ? getText("pisell2.saas.team-members.deactivate") : getText("pisell2.saas.team-members.activate"),
					onClick: () => handleToggleStatus(record)
				}, {
					key: "delete",
					label: getText("pisell2.saas.team-members.delete"),
					danger: true,
					onClick: () => handleDeleteMember(record)
				}];
				return /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, null, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
					type: "text",
					icon: /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, { type: "pisell2-edit-05" }),
					onClick: () => handleEditMember(record)
				}), /* @__PURE__ */ react.default.createElement(_pisell_materials.Dropdown, {
					menu: { items },
					trigger: ["click"]
				}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
					type: "text",
					icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.MoreOutlined, null)
				})));
			}
		}
	], [
		getText,
		getLocaleText,
		handleEditMember,
		handleDeleteMember,
		handleToggleStatus
	]);
	const roleOptions = (0, react.useMemo)(() => (rolesRequest.data || []).map((role) => ({
		label: getLocaleText(role.name),
		value: role.id
	})), [rolesRequest.data, getLocaleText]);
	const statusOptions = (0, react.useMemo)(() => [{
		label: getText("pisell2.saas.team-members.status.active"),
		value: "active"
	}, {
		label: getText("pisell2.saas.team-members.status.inactive"),
		value: "inactive"
	}], [getText]);
	return /* @__PURE__ */ react.default.createElement("div", {
		className: (0, classnames.default)("saas-team-members", className),
		style
	}, /* @__PURE__ */ react.default.createElement("div", { className: "saas-team-members-header" }, /* @__PURE__ */ react.default.createElement("div", { className: "saas-team-members-header-left" }, /* @__PURE__ */ react.default.createElement("h2", null, getText("pisell2.saas.team-members.title")), /* @__PURE__ */ react.default.createElement("p", null, getText("pisell2.saas.team-members.subtitle"))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-team-members-header-right" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
		type: "primary",
		icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.PlusOutlined, null),
		onClick: handleAddMember
	}, getText("pisell2.saas.team-members.add")))), /* @__PURE__ */ react.default.createElement("div", { className: "saas-team-members-filters" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Input, {
		placeholder: getText("pisell2.saas.team-members.search-placeholder"),
		allowClear: true,
		value: searchText,
		onChange: (e) => setSearchText(e.target.value),
		style: { width: 300 },
		prefix: /* @__PURE__ */ react.default.createElement(_ant_design_icons.SearchOutlined, null),
		size: "large"
	}), /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, null, /* @__PURE__ */ react.default.createElement(_pisell_materials.Select, {
		mode: "multiple",
		placeholder: getText("pisell2.saas.team-members.filter.all-roles"),
		style: { minWidth: 200 },
		options: roleOptions,
		value: filters.roles || [],
		onChange: (value) => setFilters(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, filters), {}, { roles: value })),
		allowClear: true,
		size: "large"
	}), /* @__PURE__ */ react.default.createElement(_pisell_materials.Select, {
		placeholder: getText("pisell2.saas.team-members.filter.all-status"),
		style: { width: 150 },
		options: statusOptions,
		value: filters.status,
		onChange: (value) => setFilters(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, filters), {}, { status: value })),
		allowClear: true,
		size: "large"
	}))), /* @__PURE__ */ react.default.createElement(_pisell_materials.Table, {
		columns,
		dataSource: ((_membersRequest$data = membersRequest.data) === null || _membersRequest$data === void 0 ? void 0 : _membersRequest$data.list) || [],
		rowKey: "id",
		loading: membersRequest.loading,
		scroll: { autoCalc: true },
		bordered: true,
		pagination: {
			size: "middle",
			current: currentPage,
			pageSize,
			total: ((_membersRequest$data2 = membersRequest.data) === null || _membersRequest$data2 === void 0 ? void 0 : _membersRequest$data2.count) || 0,
			showSizeChanger: true,
			showTotal: (total) => getText("pisell2.saas.team-members.pagination.total").replace("{total}", String(total)),
			onChange: ({ page, size }) => {
				setCurrentPage(page);
				setPageSize(size);
			}
		},
		locale: { emptyText: /* @__PURE__ */ react.default.createElement(_pisell_materials.Empty, { description: getText("pisell2.saas.team-members.empty.description") }) }
	}), /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		visible: drawerVisible,
		mode: drawerMode,
		currentMember,
		roleOptions,
		roles: rolesRequest.data || [],
		onClose: handleDrawerClose,
		onSubmit: handleSubmit,
		loading: createRequest.loading || updateRequest.loading,
		getText,
		getLocaleText,
		tenantId,
		mypisellData,
		locale: _locale
	}), /* @__PURE__ */ react.default.createElement(antd.ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
};
//#endregion
exports.default = SaasTeamMembers;
