import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { _objectWithoutProperties } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { request } from "../../utils/index.js";
import locales$1 from "./locales.js";
import { activateTeamMember, createTeamMember, deactivateTeamMember, deleteTeamMember, getRoles, getTeamMembers, updateTeamMember } from "./serve.js";
import MemberDrawer from "./components/MemberDrawer/index.js";
import dayjs from "dayjs";
import React, { useCallback, useMemo, useState } from "react";
import { ConfigProvider, Modal } from "antd";
import { locales } from "@pisell/utils";
import { Button as Button$1, Dropdown as Dropdown$1, Empty as Empty$1, Icon, Input as Input$1, Popover as Popover$1, Select as Select$1, Space as Space$1, Table as Table$1, Tag as Tag$1, message as message$1 } from "@pisell/materials";
import classNames from "classnames";
import { useRequest } from "ahooks";
import { MoreOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
import "./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] = useState("");
	const [filters, setFilters] = useState({});
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [drawerMode, setDrawerMode] = useState("create");
	const [currentMember, setCurrentMember] = useState(null);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modal, contextHolder] = Modal.useModal();
	const context = useEngineContext();
	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) 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";
	locales.init(locales$1, _locale);
	const getText = locales.getText;
	const getLocaleText = 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 } = 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 = 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 getTeamMembers(params);
	}, { refreshDeps: [
		currentPage,
		pageSize,
		searchText,
		filters
	] });
	const rolesRequest = useRequest(getRoles);
	const createRequest = useRequest(createTeamMember, {
		manual: true,
		onSuccess: () => {
			setDrawerVisible(false);
			membersRequest.refresh();
		}
	});
	const updateRequest = useRequest((id, data) => updateTeamMember(id, data), {
		manual: true,
		onSuccess: () => {
			setDrawerVisible(false);
			membersRequest.refresh();
		}
	});
	const deleteRequest = useRequest(deleteTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const activateRequest = useRequest(activateTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const deactivateRequest = useRequest(deactivateTeamMember, {
		manual: true,
		onSuccess: () => {
			membersRequest.refresh();
		}
	});
	const handleAddMember = useCallback(() => {
		setDrawerMode("create");
		setCurrentMember(null);
		setDrawerVisible(true);
	}, []);
	const handleEditMember = useCallback((member) => {
		setDrawerMode("edit");
		setCurrentMember(member);
		setDrawerVisible(true);
	}, []);
	const handleDeleteMember = useCallback((member) => {
		if (member.type === "founder") {
			message$1.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 = _asyncToGenerator(function* () {
					yield deleteRequest.runAsync(member.id);
				});
				return function onOk() {
					return _ref.apply(this, arguments);
				};
			}()
		});
	}, [getText, deleteRequest]);
	const handleToggleStatus = useCallback((member) => {
		if (member.type === "founder" && member.status === "active") {
			message$1.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 = _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 = useCallback(function() {
		var _ref3 = _asyncToGenerator(function* (values) {
			if (drawerMode === "create") yield createRequest.runAsync(values);
			else if (currentMember) {
				const { email, password } = values, updateData = _objectWithoutProperties(values, _excluded);
				yield updateRequest.runAsync(currentMember.id, updateData);
			}
		});
		return function(_x) {
			return _ref3.apply(this, arguments);
		};
	}(), [
		drawerMode,
		currentMember,
		createRequest,
		updateRequest
	]);
	const handleDrawerClose = useCallback(() => {
		setDrawerVisible(false);
		setCurrentMember(null);
	}, []);
	const columns = useMemo(() => [
		{
			title: getText("pisell2.saas.team-members.column.display-name"),
			dataIndex: "nickname",
			key: "nickname",
			fixed: "left",
			width: 220,
			render: (text, record) => /* @__PURE__ */ React.createElement(Space$1, null, /* @__PURE__ */ React.createElement("span", null, text), record.type === "founder" && /* @__PURE__ */ React.createElement(Tag$1, { 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.createElement(Space$1, {
					size: 4,
					wrap: true
				}, displayRoles.map((role) => /* @__PURE__ */ React.createElement(Tag$1, { key: role.id }, getLocaleText(role.name))), remainingCount > 0 && /* @__PURE__ */ React.createElement(Popover$1, { content: /* @__PURE__ */ React.createElement(Space$1, {
					size: 4,
					wrap: true
				}, roles.map((role) => /* @__PURE__ */ React.createElement(Tag$1, { key: role.id }, getLocaleText(role.name)))) }, /* @__PURE__ */ React.createElement(Tag$1, 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.createElement(Tag$1, {
				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) => dayjs(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.createElement(Space$1, null, /* @__PURE__ */ React.createElement(Button$1, {
					type: "text",
					icon: /* @__PURE__ */ React.createElement(Icon, { type: "pisell2-edit-05" }),
					onClick: () => handleEditMember(record)
				}), /* @__PURE__ */ React.createElement(Dropdown$1, {
					menu: { items },
					trigger: ["click"]
				}, /* @__PURE__ */ React.createElement(Button$1, {
					type: "text",
					icon: /* @__PURE__ */ React.createElement(MoreOutlined, null)
				})));
			}
		}
	], [
		getText,
		getLocaleText,
		handleEditMember,
		handleDeleteMember,
		handleToggleStatus
	]);
	const roleOptions = useMemo(() => (rolesRequest.data || []).map((role) => ({
		label: getLocaleText(role.name),
		value: role.id
	})), [rolesRequest.data, getLocaleText]);
	const statusOptions = 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.createElement("div", {
		className: classNames("saas-team-members", className),
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "saas-team-members-header" }, /* @__PURE__ */ React.createElement("div", { className: "saas-team-members-header-left" }, /* @__PURE__ */ React.createElement("h2", null, getText("pisell2.saas.team-members.title")), /* @__PURE__ */ React.createElement("p", null, getText("pisell2.saas.team-members.subtitle"))), /* @__PURE__ */ React.createElement("div", { className: "saas-team-members-header-right" }, /* @__PURE__ */ React.createElement(Button$1, {
		type: "primary",
		icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
		onClick: handleAddMember
	}, getText("pisell2.saas.team-members.add")))), /* @__PURE__ */ React.createElement("div", { className: "saas-team-members-filters" }, /* @__PURE__ */ React.createElement(Input$1, {
		placeholder: getText("pisell2.saas.team-members.search-placeholder"),
		allowClear: true,
		value: searchText,
		onChange: (e) => setSearchText(e.target.value),
		style: { width: 300 },
		prefix: /* @__PURE__ */ React.createElement(SearchOutlined, null),
		size: "large"
	}), /* @__PURE__ */ React.createElement(Space$1, null, /* @__PURE__ */ React.createElement(Select$1, {
		mode: "multiple",
		placeholder: getText("pisell2.saas.team-members.filter.all-roles"),
		style: { minWidth: 200 },
		options: roleOptions,
		value: filters.roles || [],
		onChange: (value) => setFilters(_objectSpread2(_objectSpread2({}, filters), {}, { roles: value })),
		allowClear: true,
		size: "large"
	}), /* @__PURE__ */ React.createElement(Select$1, {
		placeholder: getText("pisell2.saas.team-members.filter.all-status"),
		style: { width: 150 },
		options: statusOptions,
		value: filters.status,
		onChange: (value) => setFilters(_objectSpread2(_objectSpread2({}, filters), {}, { status: value })),
		allowClear: true,
		size: "large"
	}))), /* @__PURE__ */ React.createElement(Table$1, {
		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.createElement(Empty$1, { description: getText("pisell2.saas.team-members.empty.description") }) }
	}), /* @__PURE__ */ React.createElement(MemberDrawer, {
		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.createElement(ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
};
//#endregion
export { SaasTeamMembers as default };
