"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const ui = require("@contember/ui");
const react = require("react");
const EditMembership = require("./EditMembership.cjs");
const projectMemberships = require("../../queries/projectMemberships.cjs");
const updateMembership = require("../../mutations/membership/updateMembership.cjs");
const reactRouting = require("@contember/react-routing");
const EditIdentity = ({ project, rolesConfig, identityId, userListLink }) => {
  const { state: previousMembershipsState } = projectMemberships.useProjectMembershipsQuery(project, identityId);
  const [memberships, setMemberships] = react.useState([void 0]);
  const updateMembership$1 = updateMembership.useUpdateProjectMembership();
  react.useEffect(() => {
    setMemberships((currentMemberships) => {
      if (previousMembershipsState.state === "success") {
        return previousMembershipsState.data.memberships;
      }
      return currentMemberships;
    });
  }, [previousMembershipsState]);
  const redirect = reactRouting.useRedirect();
  const addToast = ui.useShowToast();
  const [isSubmitting, setSubmitting] = react.useState(false);
  const submit = react.useCallback(
    async (e) => {
      e.preventDefault();
      setSubmitting(true);
      const membershipsToSave = memberships.filter((it) => it !== void 0);
      if (membershipsToSave.length === 0) {
        return;
      }
      const result = await updateMembership$1({ projectSlug: project, identityId, memberships: membershipsToSave });
      setSubmitting(false);
      if (result.ok) {
        addToast({
          type: "success",
          message: `Updated user's roles successfully.`,
          dismiss: true
        });
        redirect(userListLink);
      } else {
        switch (result.error.code) {
          case "NOT_MEMBER":
            return addToast({ message: `Project member not found`, type: "error", dismiss: true });
          case "INVALID_MEMBERSHIP":
            return addToast({ message: `Invalid membership definition`, type: "error", dismiss: true });
          case "PROJECT_NOT_FOUND":
            return addToast({ message: `Project not found`, type: "error", dismiss: true });
        }
      }
    },
    [memberships, updateMembership$1, project, identityId, redirect, userListLink, addToast]
  );
  const editUserMembershipProps = { project, rolesConfig, memberships, setMemberships };
  return /* @__PURE__ */ jsxRuntime.jsx("form", { onSubmit: submit, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { gap: "large", children: [
    /* @__PURE__ */ jsxRuntime.jsx(EditMembership.EditMembership, { ...editUserMembershipProps }),
    /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { display: "block", distinction: "primary", type: "submit", disabled: isSubmitting, children: "Save" })
  ] }) });
};
exports.EditIdentity = EditIdentity;
//# sourceMappingURL=EditIdentity.cjs.map
