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