import { jsx, jsxs } from "react/jsx-runtime";
import { useShowToast, Stack, FieldContainer, TextInput, Button } from "@contember/ui";
import { useState, useCallback } from "react";
import { useForm } from "../../lib/useForm.js";
import { useCreateApiKey } from "../../mutations/apiKey/createApiKey.js";
import { EditMembership } from "../member/EditMembership.js";
import { useRedirect } from "../../../routing/binding/useRedirect.js";
const initialValues = {
  description: ""
};
const CreateApiKeyForm = ({ project, rolesConfig, apiKeyListLink }) => {
  const { register, values } = useForm(initialValues);
  const redirect = useRedirect();
  const addToast = useShowToast();
  const [isSubmitting, setSubmitting] = useState(false);
  const [memberships, setMemberships] = useState([void 0]);
  const createApiKey = useCreateApiKey();
  const submit = useCallback(
    async (e) => {
      e.preventDefault();
      setSubmitting(true);
      const membershipsToSave = memberships.filter((it) => it !== void 0);
      const response = await createApiKey({
        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, values.description, project, addToast, redirect, apiKeyListLink]
  );
  const editUserMembershipProps = { project, rolesConfig, memberships, setMemberships };
  return /* @__PURE__ */ jsx("form", { onSubmit: submit, children: /* @__PURE__ */ jsxs(Stack, { children: [
    /* @__PURE__ */ jsx(FieldContainer, { label: "Description", children: /* @__PURE__ */ jsx(TextInput, { ...register("description") }) }),
    /* @__PURE__ */ jsx(EditMembership, { ...editUserMembershipProps }),
    /* @__PURE__ */ jsx(Button, { display: "block", distinction: "primary", type: "submit", disabled: isSubmitting, children: "Create API key" })
  ] }) });
};
export {
  CreateApiKeyForm
};
//# sourceMappingURL=CreateApiKeyForm.js.map
