import { useState, useCallback, createElement } from "react";
import { useShowToast, Stack, FieldContainer, TextInput, Button } from "@contember/ui";
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__ */ createElement("form", {
    onSubmit: submit
  }, /* @__PURE__ */ createElement(Stack, {
    direction: "vertical",
    gap: "large"
  }, /* @__PURE__ */ createElement(FieldContainer, {
    label: "Description"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("description")
  })), /* @__PURE__ */ createElement(EditMembership, {
    ...editUserMembershipProps
  }), /* @__PURE__ */ createElement(Button, {
    distinction: "primary",
    size: "large",
    type: "submit",
    disabled: isSubmitting
  }, "Create API key")));
};
export { CreateApiKeyForm };
//# sourceMappingURL=CreateApiKeyForm.js.map
