var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasTeamMembers/index.tsx
var saasTeamMembers_exports = {};
__export(saasTeamMembers_exports, {
  default: () => saasTeamMembers_default
});
module.exports = __toCommonJS(saasTeamMembers_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_icons = require("@ant-design/icons");
var import_utils = require("@pisell/utils");
var import_classnames = __toESM(require("classnames"));
var import_dayjs = __toESM(require("dayjs"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_serve = require("./serve");
var import_utils2 = require("../../utils");
var import_MemberDrawer = __toESM(require("./components/MemberDrawer"));
var import_index = require("./index.less");
var SaasTeamMembers = ({
  className,
  style
}) => {
  var _a, _b, _c, _d, _e;
  const [searchText, setSearchText] = (0, import_react.useState)("");
  const [filters, setFilters] = (0, import_react.useState)({});
  const [drawerVisible, setDrawerVisible] = (0, import_react.useState)(false);
  const [drawerMode, setDrawerMode] = (0, import_react.useState)("create");
  const [currentMember, setCurrentMember] = (0, import_react.useState)(
    null
  );
  const [currentPage, setCurrentPage] = (0, import_react.useState)(1);
  const [pageSize, setPageSize] = (0, import_react.useState)(10);
  const [modal, contextHolder] = import_antd.Modal.useModal();
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  if (utils == null ? void 0 : utils.request) {
    import_utils2.request.setRequest(utils.request);
  }
  const _locale = ((_c = (_b = context == null ? void 0 : context.engine) == null ? void 0 : _b.props) == null ? void 0 : _c.locale) || "en";
  import_utils.locales.init(import_locales.default, _locale);
  const getText = import_utils.locales.getText;
  const getLocaleText = (0, import_react.useCallback)(
    (text) => {
      var _a2;
      if (!text) return "";
      if (typeof text === "string") return text;
      const { translation } = ((_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) || {};
      return translation(text);
    },
    [context]
  );
  const { tenantId, mypisellData } = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2, _e2;
    const core = (_d2 = (_c2 = (_b2 = (_a2 = utils.store) == null ? void 0 : _a2.getState) == null ? void 0 : _b2.call(_a2)) == null ? void 0 : _c2.core) == null ? void 0 : _d2.core;
    return {
      tenantId: (_e2 = core == null ? void 0 : core.tenant) == null ? void 0 : _e2.tenant_id,
      mypisellData: core == null ? void 0 : core.mypisell_data
    };
  }, [utils.store]);
  const membersRequest = (0, import_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 (0, import_serve.getTeamMembers)(params);
    },
    {
      refreshDeps: [currentPage, pageSize, searchText, filters]
    }
  );
  const rolesRequest = (0, import_ahooks.useRequest)(import_serve.getRoles);
  const createRequest = (0, import_ahooks.useRequest)(import_serve.createTeamMember, {
    manual: true,
    onSuccess: () => {
      setDrawerVisible(false);
      membersRequest.refresh();
    }
  });
  const updateRequest = (0, import_ahooks.useRequest)(
    (id, data) => (0, import_serve.updateTeamMember)(id, data),
    {
      manual: true,
      onSuccess: () => {
        setDrawerVisible(false);
        membersRequest.refresh();
      }
    }
  );
  const deleteRequest = (0, import_ahooks.useRequest)(import_serve.deleteTeamMember, {
    manual: true,
    onSuccess: () => {
      membersRequest.refresh();
    }
  });
  const activateRequest = (0, import_ahooks.useRequest)(import_serve.activateTeamMember, {
    manual: true,
    onSuccess: () => {
      membersRequest.refresh();
    }
  });
  const deactivateRequest = (0, import_ahooks.useRequest)(import_serve.deactivateTeamMember, {
    manual: true,
    onSuccess: () => {
      membersRequest.refresh();
    }
  });
  const handleAddMember = (0, import_react.useCallback)(() => {
    setDrawerMode("create");
    setCurrentMember(null);
    setDrawerVisible(true);
  }, []);
  const handleEditMember = (0, import_react.useCallback)((member) => {
    setDrawerMode("edit");
    setCurrentMember(member);
    setDrawerVisible(true);
  }, []);
  const handleDeleteMember = (0, import_react.useCallback)(
    (member) => {
      if (member.type === "founder") {
        import_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: async () => {
          await deleteRequest.runAsync(member.id);
        }
      });
    },
    [getText, deleteRequest]
  );
  const handleToggleStatus = (0, import_react.useCallback)(
    (member) => {
      if (member.type === "founder" && member.status === "active") {
        import_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: async () => {
            await deactivateRequest.runAsync(member.id);
          }
        });
      } else {
        activateRequest.run(member.id);
      }
    },
    [getText, activateRequest, deactivateRequest]
  );
  const handleSubmit = (0, import_react.useCallback)(
    async (values) => {
      if (drawerMode === "create") {
        await createRequest.runAsync(values);
      } else if (currentMember) {
        const { email, password, ...updateData } = values;
        await updateRequest.runAsync(currentMember.id, updateData);
      }
    },
    [drawerMode, currentMember, createRequest, updateRequest]
  );
  const handleDrawerClose = (0, import_react.useCallback)(() => {
    setDrawerVisible(false);
    setCurrentMember(null);
  }, []);
  const columns = (0, import_react.useMemo)(
    () => [
      {
        title: getText("pisell2.saas.team-members.column.name"),
        dataIndex: "nickname",
        key: "nickname",
        fixed: "left",
        width: 220,
        render: (text, record) => /* @__PURE__ */ import_react.default.createElement(import_materials.Space, null, /* @__PURE__ */ import_react.default.createElement("span", null, text), record.type === "founder" && /* @__PURE__ */ import_react.default.createElement(import_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__ */ import_react.default.createElement(import_materials.Space, { size: 4, wrap: true }, displayRoles.map((role) => /* @__PURE__ */ import_react.default.createElement(import_materials.Tag, { key: role.id }, getLocaleText(role.name))), remainingCount > 0 && /* @__PURE__ */ import_react.default.createElement(
            import_materials.Popover,
            {
              content: /* @__PURE__ */ import_react.default.createElement(import_materials.Space, { size: 4, wrap: true }, roles.map((role) => /* @__PURE__ */ import_react.default.createElement(import_materials.Tag, { key: role.id }, getLocaleText(role.name))))
            },
            /* @__PURE__ */ import_react.default.createElement(import_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__ */ import_react.default.createElement(
          import_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, import_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__ */ import_react.default.createElement(import_materials.Space, null, /* @__PURE__ */ import_react.default.createElement(
            import_materials.Button,
            {
              type: "text",
              icon: /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: "pisell2-edit-05" }),
              onClick: () => handleEditMember(record)
            }
          ), /* @__PURE__ */ import_react.default.createElement(import_materials.Dropdown, { menu: { items }, trigger: ["click"] }, /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "text", icon: /* @__PURE__ */ import_react.default.createElement(import_icons.MoreOutlined, null) })));
        }
      }
    ],
    [
      getText,
      getLocaleText,
      handleEditMember,
      handleDeleteMember,
      handleToggleStatus
    ]
  );
  const roleOptions = (0, import_react.useMemo)(
    () => (rolesRequest.data || []).map((role) => ({
      label: getLocaleText(role.name),
      value: role.id
    })),
    [rolesRequest.data, getLocaleText]
  );
  const statusOptions = (0, import_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__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)("saas-team-members", className), style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-team-members-header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-team-members-header-left" }, /* @__PURE__ */ import_react.default.createElement("h2", null, getText("pisell2.saas.team-members.title")), /* @__PURE__ */ import_react.default.createElement("p", null, getText("pisell2.saas.team-members.subtitle"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-team-members-header-right" }, /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      type: "primary",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
      onClick: handleAddMember
    },
    getText("pisell2.saas.team-members.add")
  ))), /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-team-members-filters" }, /* @__PURE__ */ import_react.default.createElement(
    import_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__ */ import_react.default.createElement(import_icons.SearchOutlined, null),
      size: "large"
    }
  ), /* @__PURE__ */ import_react.default.createElement(import_materials.Space, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.Select,
    {
      mode: "multiple",
      placeholder: getText("pisell2.saas.team-members.filter.all-roles"),
      style: { minWidth: 200 },
      options: roleOptions,
      value: filters.roles || [],
      onChange: (value) => setFilters({ ...filters, roles: value }),
      allowClear: true,
      size: "large"
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Select,
    {
      placeholder: getText("pisell2.saas.team-members.filter.all-status"),
      style: { width: 150 },
      options: statusOptions,
      value: filters.status,
      onChange: (value) => setFilters({ ...filters, status: value }),
      allowClear: true,
      size: "large"
    }
  ))), /* @__PURE__ */ import_react.default.createElement(
    import_materials.Table,
    {
      columns,
      dataSource: ((_d = membersRequest.data) == null ? void 0 : _d.list) || [],
      rowKey: "id",
      loading: membersRequest.loading,
      scroll: { autoCalc: true },
      bordered: true,
      pagination: {
        size: "middle",
        current: currentPage,
        pageSize,
        total: ((_e = membersRequest.data) == null ? void 0 : _e.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__ */ import_react.default.createElement(
          import_materials.Empty,
          {
            description: getText(
              "pisell2.saas.team-members.empty.description"
            )
          }
        )
      }
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_MemberDrawer.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__ */ import_react.default.createElement(import_antd.ConfigProvider, { prefixCls: "pisell-lowcode" }, contextHolder));
};
var saasTeamMembers_default = SaasTeamMembers;
