import { useCallback, createElement } from "react";
import { useShowToast, Stack, FieldContainer, TextInput, Button } from "@contember/ui";
import { useResetPassword } from "../../mutations/password/resetPassword.js";
import { useRedirect } from "../../../routing/binding/useRedirect.js";
import { useForm } from "../../lib/useForm.js";
const initialValues = {
  password: "",
  passwordAgain: ""
};
const ResetPasswordForm = ({ redirectOnSuccess, token }) => {
  const redirect = useRedirect();
  const addToast = useShowToast();
  const resetPassword = useResetPassword();
  const { register, isSubmitting, onSubmit } = useForm(initialValues, useCallback(async (values) => {
    if (values.password !== values.passwordAgain) {
      return addToast({ message: `Passwords does not match`, type: "error", dismiss: true });
    }
    const response = await resetPassword({
      password: values.password,
      token
    });
    if (response.ok) {
      addToast({
        type: "success",
        message: `Password successfully set.`,
        dismiss: true
      });
      redirect(redirectOnSuccess);
    } else {
      switch (response.error.code) {
        case "PASSWORD_TOO_WEAK":
          return addToast({ message: `Password is too weak`, type: "error", dismiss: true });
        case "TOKEN_NOT_FOUND":
        case "TOKEN_USED":
        case "TOKEN_EXPIRED":
          return addToast({ message: `Reset link is not valid`, type: "error", dismiss: true });
      }
    }
  }, [addToast, redirect, redirectOnSuccess, resetPassword, token]));
  return /* @__PURE__ */ createElement("form", {
    onSubmit
  }, /* @__PURE__ */ createElement(Stack, {
    direction: "vertical",
    gap: "large"
  }, /* @__PURE__ */ createElement(FieldContainer, {
    label: "Password"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("password"),
    required: true,
    type: "password"
  })), /* @__PURE__ */ createElement(FieldContainer, {
    label: "Password again"
  }, /* @__PURE__ */ createElement(TextInput, {
    ...register("passwordAgain"),
    required: true,
    type: "password"
  })), /* @__PURE__ */ createElement(FieldContainer, {
    label: void 0
  }, /* @__PURE__ */ createElement(Button, {
    distinction: "primary",
    type: "submit",
    disabled: isSubmitting
  }, "Set new password"))));
};
export { ResetPasswordForm };
//# sourceMappingURL=ResetPasswordForm.js.map
