import { jsx, jsxs } from "react/jsx-runtime";
import { useShowToast, Stack, Button } from "@contember/ui";
import { useState, useEffect, useCallback } from "react";
import { EditMembership } from "./EditMembership.js";
import { useProjectMembershipsQuery } from "../../queries/projectMemberships.js";
import { useUpdateProjectMembership } from "../../mutations/membership/updateMembership.js";
import { useRedirect } from "@contember/react-routing";
const EditIdentity = ({ project, rolesConfig, identityId, userListLink }) => {
  const { state: previousMembershipsState } = useProjectMembershipsQuery(project, identityId);
  const [memberships, setMemberships] = useState([void 0]);
  const updateMembership = useUpdateProjectMembership();
  useEffect(() => {
    setMemberships((currentMemberships) => {
      if (previousMembershipsState.state === "success") {
        return previousMembershipsState.data.memberships;
      }
      return currentMemberships;
    });
  }, [previousMembershipsState]);
  const redirect = useRedirect();
  const addToast = useShowToast();
  const [isSubmitting, setSubmitting] = useState(false);
  const submit = useCallback(
    async (e) => {
      e.preventDefault();
      setSubmitting(true);
      const membershipsToSave = memberships.filter((it) => it !== void 0);
      if (membershipsToSave.length === 0) {
        return;
      }
      const result = await updateMembership({ 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, project, identityId, redirect, userListLink, addToast]
  );
  const editUserMembershipProps = { project, rolesConfig, memberships, setMemberships };
  return /* @__PURE__ */ jsx("form", { onSubmit: submit, children: /* @__PURE__ */ jsxs(Stack, { gap: "large", children: [
    /* @__PURE__ */ jsx(EditMembership, { ...editUserMembershipProps }),
    /* @__PURE__ */ jsx(Button, { display: "block", distinction: "primary", type: "submit", disabled: isSubmitting, children: "Save" })
  ] }) });
};
export {
  EditIdentity
};
//# sourceMappingURL=EditIdentity.js.map
