"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 useForm = require("../../lib/useForm.cjs");
const createApiKey = require("../../mutations/apiKey/createApiKey.cjs");
const EditMembership = require("../member/EditMembership.cjs");
const reactRouting = require("@contember/react-routing");
const initialValues = {
  description: ""
};
const CreateApiKeyForm = ({ project, rolesConfig, apiKeyListLink }) => {
  const { register, values } = useForm.useForm(initialValues);
  const redirect = reactRouting.useRedirect();
  const addToast = ui.useShowToast();
  const [isSubmitting, setSubmitting] = react.useState(false);
  const [memberships, setMemberships] = react.useState([void 0]);
  const createApiKey$1 = createApiKey.useCreateApiKey();
  const submit = react.useCallback(
    async (e) => {
      e.preventDefault();
      setSubmitting(true);
      const membershipsToSave = memberships.filter((it) => it !== void 0);
      const response = await createApiKey$1({
        description: values.description,
        memberships: membershipsToSave,
        projectSlug: project
      });
      setSubmitting(false);
      if (response.ok) {
        addToast({
          type: "success",
          message: `API key has been created. Save following token: ${response.result.apiKey.token}`
        });
        redirect(apiKeyListLink);
      } else {
        switch (response.error.code) {
          case "INVALID_MEMBERSHIP":
            return addToast({ message: `Invalid membership definition`, type: "error" });
          case "PROJECT_NOT_FOUND":
            return addToast({ message: `Project not found`, type: "error" });
        }
      }
    },
    [memberships, createApiKey$1, values.description, project, addToast, redirect, apiKeyListLink]
  );
  const editUserMembershipProps = { project, rolesConfig, memberships, setMemberships };
  return /* @__PURE__ */ jsxRuntime.jsx("form", { onSubmit: submit, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(ui.FieldContainer, { label: "Description", children: /* @__PURE__ */ jsxRuntime.jsx(ui.TextInput, { ...register("description") }) }),
    /* @__PURE__ */ jsxRuntime.jsx(EditMembership.EditMembership, { ...editUserMembershipProps }),
    /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { display: "block", distinction: "primary", type: "submit", disabled: isSubmitting, children: "Create API key" })
  ] }) });
};
exports.CreateApiKeyForm = CreateApiKeyForm;
//# sourceMappingURL=CreateApiKeyForm.cjs.map
