import { jsx, jsxs } from "react/jsx-runtime";
import { useShowToast, Stack, FieldContainer, PasswordInput, Button } from "@contember/ui";
import { useCallback } from "react";
import { useResetPassword } from "../../mutations/password/resetPassword.js";
import { useRedirect } from "@contember/react-routing";
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__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs(Stack, { gap: "large", children: [
    /* @__PURE__ */ jsx(FieldContainer, { label: "Password", children: /* @__PURE__ */ jsx(PasswordInput, { ...register("password"), required: true }) }),
    /* @__PURE__ */ jsx(FieldContainer, { label: "Password again", children: /* @__PURE__ */ jsx(PasswordInput, { ...register("passwordAgain"), required: true }) }),
    /* @__PURE__ */ jsx(FieldContainer, { label: void 0, children: /* @__PURE__ */ jsx(Button, { distinction: "primary", type: "submit", disabled: isSubmitting, children: "Set new password" }) })
  ] }) });
};
export {
  ResetPasswordForm
};
//# sourceMappingURL=ResetPasswordForm.js.map
