import { useState } from "@saasquatch/universal-hooks";
import jsonpointer from "jsonpointer";
import { useChangePasswordMutation, useUserIdentity, } from "@saasquatch/component-boilerplate";
export function usePortalChangePassword(props) {
  var _a, _b, _c, _d, _e, _f, _g;
  const [request, { loading, errors, data }] = useChangePasswordMutation();
  const [open, setOpen] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const user = useUserIdentity();
  const submit = async (event) => {
    var _a, _b;
    setSuccess(false);
    const formData = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.formData;
    formData === null || formData === void 0 ? void 0 : formData.forEach((value, key) => {
      jsonpointer.set(formData, key, value);
    });
    if (!(user === null || user === void 0 ? void 0 : user.jwt)) {
      setError(props.invalidSessionErrorText);
      return;
    }
    if (formData.password !== formData.confirmPassword) {
      setError(props.nonMatchingPasswordErrorText);
      return;
    }
    setError("");
    const variables = {
      password: formData.password,
    };
    const result = await request(variables);
    if (!(result instanceof Error) && ((_b = result.changeManagedIdentityPassword) === null || _b === void 0 ? void 0 : _b.success)) {
      setSuccess(true);
    }
  };
  return {
    states: {
      open,
      loading,
      success,
      error: error || ((_d = (_c = (_b = (_a = errors === null || errors === void 0 ? void 0 : errors.response) === null || _a === void 0 ? void 0 : _a.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.extensions) === null || _d === void 0 ? void 0 : _d.message) || ((_g = (_f = (_e = errors === null || errors === void 0 ? void 0 : errors.response) === null || _e === void 0 ? void 0 : _e.errors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.message),
      content: {
        modalChangePasswordHeader: props.modalChangePasswordHeader,
        cancelText: props.cancelText,
        changePasswordButtonText: props.changePasswordButtonText,
        passwordFieldLabel: props.passwordFieldLabel,
        confirmPasswordFieldLabel: props.confirmPasswordFieldLabel,
        successMessage: props.successMessage,
        portalChangePasswordHeader: props.portalChangePasswordHeader,
        portalChangePasswordButtonText: props.portalChangePasswordButtonText,
        meetsRequirementsText: props.meetsRequirementsText,
        doesNotMeetRequirementsText: props.doesNotMeetRequirementsText,
        minErrorText: props.minErrorText,
        uppercaseErrorText: props.uppercaseErrorText,
        lowercaseErrorText: props.lowercaseErrorText,
        hasErrorText: props.hasErrorText,
      },
    },
    data: {},
    callbacks: {
      setOpen,
      submit,
    },
  };
}
