import {
  getApiKeyTypeFromPathname
} from "./chunk-XFR5JLNF.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCreateApiKey
} from "./chunk-YKDEE7ZL.js";
import "./chunk-DL2ZIXBO.js";
import "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/api-key-management/api-key-management-create/api-key-management-create.tsx
import { useLocation } from "react-router-dom";

// src/pages/api-key-management/api-key-management-create/components/api-key-create-form/api-key-create-form.tsx
import { Fragment, useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeSlash } from "@medusajs/icons";
import { Button, Heading, Input, Prompt, Text, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var ApiKeyCreateSchema = zod.object({
  title: zod.string().min(1)
});
function getRedactedKey(key) {
  if (!key) {
    return "";
  }
  const firstThree = key.slice(0, 4);
  const lastTwo = key.slice(-2);
  return `${firstThree}${"\u2022".repeat(key.length - 6)}${lastTwo}`;
}
var ApiKeyCreateForm = ({ keyType }) => {
  const [createdKey, setCreatedKey] = useState(null);
  const [showRedactedKey, setShowRedactedKey] = useState(true);
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      title: ""
    },
    resolver: zodResolver(ApiKeyCreateSchema)
  });
  const { mutateAsync, isPending } = useCreateApiKey();
  const handleSubmit = form.handleSubmit(async (values) => {
    await mutateAsync(
      // @ts-ignore
      { title: values.title, type: keyType },
      {
        onSuccess: ({ api_key }) => {
          toast.success(t("apiKeyManagement.create.successToast"));
          switch (keyType) {
            case "publishable" /* PUBLISHABLE */:
              handleSuccess(`/settings/publishable-api-keys/${api_key.id}`);
              break;
            case "secret" /* SECRET */:
              setCreatedKey(api_key);
              break;
          }
        },
        onError: (err) => {
          toast.error(err.message);
        }
      }
    );
  });
  const handleCopyToken = () => {
    if (!createdKey) {
      toast.error(t("apiKeyManagement.create.copySecretTokenFailure"));
    }
    navigator.clipboard.writeText(createdKey?.token ?? "");
    toast.success(t("apiKeyManagement.create.copySecretTokenSuccess"));
  };
  const handleGoToSecretKey = () => {
    if (!createdKey) {
      return;
    }
    handleSuccess(`/settings/secret-api-keys/${createdKey.id}`);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      RouteFocusModal.Form,
      {
        form,
        "data-testid": `${keyType}-api-key-create-form`,
        children: /* @__PURE__ */ jsxs(
          KeyboundForm,
          {
            className: "flex h-full flex-col overflow-hidden",
            onSubmit: handleSubmit,
            children: [
              /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": `${keyType}-api-key-create-header` }),
              /* @__PURE__ */ jsx(
                RouteFocusModal.Body,
                {
                  className: "flex flex-1 flex-col overflow-hidden",
                  "data-testid": `${keyType}-api-key-create-body`,
                  children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16", children: [
                    /* @__PURE__ */ jsxs("div", { children: [
                      /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { "data-testid": `${keyType}-api-key-create-title`, children: keyType === "publishable" /* PUBLISHABLE */ ? t("apiKeyManagement.create.createPublishableHeader") : t("apiKeyManagement.create.createSecretHeader") }) }),
                      /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(
                        Text,
                        {
                          size: "small",
                          className: "text-ui-fg-subtle",
                          "data-testid": `${keyType}-api-key-create-description`,
                          children: keyType === "publishable" /* PUBLISHABLE */ ? t("apiKeyManagement.create.createPublishableHint") : t("apiKeyManagement.create.createSecretHint")
                        }
                      ) })
                    ] }),
                    /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-4", children: /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "title",
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": `${keyType}-api-key-create-title-item`, children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": `${keyType}-api-key-create-title-label`, children: t("fields.title") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": `${keyType}-api-key-create-title-control`, children: /* @__PURE__ */ jsx(
                              Input,
                              {
                                ...field,
                                "data-testid": `${keyType}-api-key-create-title-input`
                              }
                            ) }),
                            /* @__PURE__ */ jsx(
                              Form.ErrorMessage,
                              {
                                "data-testid": `${keyType}-api-key-create-title-error`
                              }
                            )
                          ] });
                        }
                      }
                    ) })
                  ] }) })
                }
              ),
              /* @__PURE__ */ jsx(RouteFocusModal.Footer, { "data-testid": `${keyType}-api-key-create-footer`, children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
                /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "small",
                    variant: "secondary",
                    "data-testid": `${keyType}-api-key-create-cancel-button`,
                    children: t("actions.cancel")
                  }
                ) }),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "small",
                    type: "submit",
                    isLoading: isPending,
                    "data-testid": `${keyType}-api-key-create-save-button`,
                    children: t("actions.save")
                  }
                )
              ] }) })
            ]
          }
        )
      }
    ),
    keyType === "secret" /* SECRET */ && /* @__PURE__ */ jsx(
      Prompt,
      {
        variant: "confirmation",
        open: !!createdKey,
        "data-testid": "secret-api-key-created-prompt",
        children: /* @__PURE__ */ jsxs(
          Prompt.Content,
          {
            className: "w-fit max-w-[42.5%]",
            "data-testid": "secret-api-key-created-prompt-content",
            children: [
              /* @__PURE__ */ jsxs(Prompt.Header, { "data-testid": "secret-api-key-created-prompt-header", children: [
                /* @__PURE__ */ jsx(Prompt.Title, { "data-testid": "secret-api-key-created-prompt-title", children: t("apiKeyManagement.create.secretKeyCreatedHeader") }),
                /* @__PURE__ */ jsx(Prompt.Description, { "data-testid": "secret-api-key-created-prompt-description", children: t("apiKeyManagement.create.secretKeyCreatedHint") })
              ] }),
              /* @__PURE__ */ jsxs(
                "div",
                {
                  className: "flex flex-col gap-y-3 px-6 py-4",
                  "data-testid": "secret-api-key-created-prompt-token-container",
                  children: [
                    /* @__PURE__ */ jsxs(
                      "div",
                      {
                        className: "grid h-8 grid-cols-[1fr_32px] items-center overflow-hidden rounded-md bg-ui-bg-component shadow-borders-base",
                        "data-testid": "secret-api-key-created-prompt-token-display",
                        children: [
                          /* @__PURE__ */ jsx(
                            "div",
                            {
                              className: "flex items-center px-2",
                              "data-testid": "secret-api-key-created-prompt-token-text",
                              children: /* @__PURE__ */ jsx(
                                Text,
                                {
                                  family: "mono",
                                  size: "small",
                                  children: showRedactedKey ? getRedactedKey(createdKey?.token) : createdKey?.token
                                }
                              )
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            "button",
                            {
                              className: "flex size-8 appearance-none items-center justify-center border-l text-ui-fg-muted transition-fg hover:bg-ui-bg-base-hover active:bg-ui-bg-base-pressed active:text-ui-fg-subtle",
                              type: "button",
                              onClick: () => setShowRedactedKey(!showRedactedKey),
                              "data-testid": "secret-api-key-created-prompt-toggle-visibility-button",
                              children: showRedactedKey ? /* @__PURE__ */ jsx(EyeSlash, {}) : /* @__PURE__ */ jsx(Eye, {})
                            }
                          )
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        size: "small",
                        variant: "secondary",
                        type: "button",
                        className: "w-full",
                        onClick: handleCopyToken,
                        "data-testid": "secret-api-key-created-prompt-copy-button",
                        children: t("apiKeyManagement.actions.copy")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ jsx(
                Prompt.Footer,
                {
                  className: "border-t py-4",
                  "data-testid": "secret-api-key-created-prompt-footer",
                  children: /* @__PURE__ */ jsx(
                    Prompt.Action,
                    {
                      onClick: handleGoToSecretKey,
                      "data-testid": "secret-api-key-created-prompt-continue-button",
                      children: t("actions.continue")
                    }
                  )
                }
              )
            ]
          }
        )
      }
    )
  ] });
};

// src/pages/api-key-management/api-key-management-create/api-key-management-create.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var ApiKeyManagementCreate = () => {
  const { pathname } = useLocation();
  const keyType = getApiKeyTypeFromPathname(pathname);
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": `${keyType}-api-key-create-modal`, children: /* @__PURE__ */ jsx2(ApiKeyCreateForm, { keyType }) });
};
export {
  ApiKeyManagementCreate as Component
};
