"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 confirmOtp = require("../../mutations/otp/confirmOtp.cjs");
const IdentityProvider = require("../../../components/Identity/IdentityProvider.cjs");
const useRedirect = require("../../../routing/binding/useRedirect.cjs");
const useForm = require("../../lib/useForm.cjs");
const initialValues = {
  token: ""
};
const ConfirmOtpForm = ({ redirectOnSuccess, onSuccess }) => {
  const redirect = useRedirect.useRedirect();
  const addToast = ui.useShowToast();
  const confirmOtp$1 = confirmOtp.useConfirmOtp();
  const refreshIdentity = react.useContext(IdentityProvider.IdentityRefreshContext);
  const { isSubmitting, onSubmit, register } = useForm.useForm(
    initialValues,
    react.useCallback(
      async (values) => {
        const response = await confirmOtp$1({ 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$1, onSuccess, redirect, redirectOnSuccess, refreshIdentity]
    )
  );
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit, children: [
    /* @__PURE__ */ jsxRuntime.jsx(ui.FieldContainer, { label: "Two-factor code", children: /* @__PURE__ */ jsxRuntime.jsx(ui.TextInput, { ...register("token"), required: true }) }),
    /* @__PURE__ */ jsxRuntime.jsx("br", {}),
    /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { distinction: "primary", type: "submit", disabled: isSubmitting, children: "Confirm two-factor authentication" })
  ] });
};
exports.ConfirmOtpForm = ConfirmOtpForm;
//# sourceMappingURL=ConfirmOtpForm.cjs.map
