import jsonpointer from "jsonpointer";
import { useState } from "@saasquatch/universal-hooks";
import { navigation, useRequestPasswordResetEmailMutation, } from "@saasquatch/component-boilerplate";
export function usePortalForgotPassword(props) {
  var _a, _b, _c, _d, _e, _f, _g;
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");
  const [request, { loading, data, errors }] = useRequestPasswordResetEmailMutation();
  const urlParams = new URLSearchParams(navigation.location.search);
  const nextPage = urlParams.get("nextPage");
  const submit = async (event) => {
    var _a;
    setError("");
    setSuccess(false);
    let formData = event.detail.formData;
    formData === null || formData === void 0 ? void 0 : formData.forEach((value, key) => {
      jsonpointer.set(formData, key, value);
    });
    const urlParams = nextPage ? { nextPage } : null;
    const redirectPath = props.redirectPath;
    const variables = { email: formData.email, urlParams, redirectPath };
    const result = await request(variables);
    if (result instanceof Error) {
      if (result.message)
        setError(props.networkErrorMessage);
      return;
    }
    if ((_a = result.requestManagedIdentityPasswordResetEmail) === null || _a === void 0 ? void 0 : _a.success) {
      setSuccess(true);
    }
  };
  return {
    states: {
      loading,
      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) ||
        error,
      success,
      loginPath: props.loginPath,
      headerText: props.headerText,
      loginText: props.loginText,
    },
    callbacks: {
      submit,
    },
  };
}
