import { useCallback, createElement, Fragment } from "react";
import { useShowToast, Heading, Stack, FieldContainer, TextInput, Spacer, Button } from "@contember/ui";
import { useChangePassword } from "../../mutations/password/changePasswords.js";
import { useForm } from "../../lib/useForm.js";
const initialValues = {
  currentPassword: "",
  newPassword: "",
  newPasswordAgain: ""
};
const ChangePassword = ({}) => {
  const changePassword = useChangePassword();
  const addToast = useShowToast();
  const { register, errors, isSubmitting, onSubmit } = useForm(initialValues, useCallback(async (val, setError, setValues) => {
    if (val.newPassword !== val.newPasswordAgain) {
      return setError("newPasswordAgain", "Password confirmation doesn't match");
    }
    const response = await changePassword({ currentPassword: val.currentPassword, newPassword: val.newPassword });
    if (response.ok) {
      addToast({
        message: "Password changed",
        type: "success",
        dismiss: true
      });
      setValues(initialValues);
    } else {
      switch (response.error.code) {
        case "INVALID_PASSWORD":
          return setError("currentPassword", "Current password is invalid");
        case "TOO_WEAK":
          return setError("newPassword", "Password is too weak");
        default:
          return addToast({
            message: "Unknown error",
            type: "error",
            dismiss: true
          });
      }
    }
  }, [addToast, changePassword]));
  return /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(Heading, {
    depth: 3
  }, "Change password"), /* @__PURE__ */ createElement("form", {
    onSubmit
  }, /* @__PURE__ */ createElement(Stack, {
    direction: "vertical",
    gap: "large"
  }, /* @__PURE__ */ createElement(FieldContainer, {
    label: "Current password",
    errors: errors.currentPassword === void 0 ? void 0 : [{ message: errors.currentPassword }]
  }, /* @__PURE__ */ createElement(TextInput, {
    type: "password",
    autoComplete: "password",
    ...register("currentPassword")
  })), /* @__PURE__ */ createElement(FieldContainer, {
    label: "New password",
    errors: errors.newPassword === void 0 ? void 0 : [{ message: errors.newPassword }]
  }, /* @__PURE__ */ createElement(TextInput, {
    type: "password",
    autoComplete: "new-password",
    ...register("newPassword")
  })), /* @__PURE__ */ createElement(FieldContainer, {
    label: "Confirm new password",
    errors: errors.newPasswordAgain === void 0 ? void 0 : [{ message: errors.newPasswordAgain }]
  }, /* @__PURE__ */ createElement(TextInput, {
    type: "password",
    autoComplete: "new-password",
    ...register("newPasswordAgain")
  })), /* @__PURE__ */ createElement(Spacer, null), /* @__PURE__ */ createElement(Button, {
    intent: "primary",
    type: "submit",
    disabled: isSubmitting
  }, "Change password"))));
};
export { ChangePassword };
//# sourceMappingURL=ChangePassword.js.map
