import { jsxDEV } from "react/jsx-dev-runtime";
import { useShowToast, FieldContainer, TextInput, Button } from "@contember/ui";
import { useCallback } from "react";
import { useIdentityMethods } from "@contember/react-identity";
import { useConfirmOtp } from "../../mutations/otp/confirmOtp.js";
import { useRedirect } from "@contember/react-routing";
import { useForm } from "../../lib/useForm.js";
const initialValues = {
  token: ""
};
const ConfirmOtpForm = ({ redirectOnSuccess, onSuccess }) => {
  const redirect = useRedirect();
  const addToast = useShowToast();
  const confirmOtp = useConfirmOtp();
  const { refreshIdentity } = useIdentityMethods();
  const { isSubmitting, onSubmit, register } = useForm(
    initialValues,
    useCallback(
      async (values) => {
        const response = await confirmOtp({ token: values.token });
        if (response.ok) {
          addToast({
            type: "success",
            message: `Two-factor authentication has been enabled`,
            dismiss: true
          });
          refreshIdentity();
          redirectOnSuccess && redirect(redirectOnSuccess);
          onSuccess && onSuccess();
        } else {
          switch (response.error.code) {
            case "INVALID_OTP_TOKEN":
              return addToast({ message: `Provided code is not valid`, type: "error" });
            case "NOT_PREPARED":
              return addToast({ message: `Two factor setup was not initialized`, type: "error" });
          }
        }
      },
      [addToast, confirmOtp, onSuccess, redirect, redirectOnSuccess, refreshIdentity]
    )
  );
  return /* @__PURE__ */ jsxDEV("form", { onSubmit, children: [
    /* @__PURE__ */ jsxDEV(FieldContainer, { label: "Two-factor code", children: /* @__PURE__ */ jsxDEV(TextInput, { ...register("token"), required: true }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/tenant/components/otp/ConfirmOtpForm.tsx",
      lineNumber: 52,
      columnNumber: 5
    }, void 0) }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/tenant/components/otp/ConfirmOtpForm.tsx",
      lineNumber: 51,
      columnNumber: 4
    }, void 0),
    /* @__PURE__ */ jsxDEV("br", {}, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/tenant/components/otp/ConfirmOtpForm.tsx",
      lineNumber: 54,
      columnNumber: 4
    }, void 0),
    /* @__PURE__ */ jsxDEV(Button, { distinction: "primary", type: "submit", disabled: isSubmitting, children: "Confirm two-factor authentication" }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/tenant/components/otp/ConfirmOtpForm.tsx",
      lineNumber: 55,
      columnNumber: 4
    }, void 0)
  ] }, void 0, true, {
    fileName: "/__w/interface/interface/packages/admin/src/tenant/components/otp/ConfirmOtpForm.tsx",
    lineNumber: 50,
    columnNumber: 3
  }, void 0);
};
export {
  ConfirmOtpForm
};
//# sourceMappingURL=ConfirmOtpForm.js.map
