import { useContext, useCallback, createElement } from "react";
import { useShowToast, FieldContainer, TextInput, Button } from "@contember/ui";
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__ */ createElement("form", {
    onSubmit
  }, /* @__PURE__ */ createElement(FieldContainer, {
    label: "Two-factor code"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("token"),
    required: true
  })), /* @__PURE__ */ createElement("br", null), /* @__PURE__ */ createElement(Button, {
    distinction: "primary",
    type: "submit",
    disabled: isSubmitting
  }, "Confirm two-factor authentication"));
};
export { ConfirmOtpForm };
//# sourceMappingURL=ConfirmOtpForm.js.map
