import { navigation, setUserIdentity, useUserIdentity, useVerifyEmailMutation, } from "@saasquatch/component-boilerplate";
import { sanitizeUrlPath } from "../../utils/utils";
import { useEffect, useState } from "@saasquatch/universal-hooks";
let globalPromise = null;
export function usePortalVerifyEmail({ nextPage, failedPage, verifySuccessText, verifyEmailText, verifyInvalidText, networkErrorMessage, continueText, }) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
  const [completed, setCompleted] = useState(false);
  const [successful, setSuccessful] = useState(false);
  const userIdent = useUserIdentity();
  const [request, { loading, data, errors }] = useVerifyEmailMutation();
  const urlParams = new URLSearchParams(navigation.location.search);
  const oobCode = urlParams.get("oobCode");
  const oobEmail = urlParams.get("email");
  const nextPageOverride = urlParams.get("nextPage");
  // derived from useMutation in component boilerplate initialState
  const disableContinue = data === undefined && errors === undefined && !!oobCode;
  // if logged out, userIdent?.managedIdentity?.emailVerified will be falsey, even if verification was successful
  const verified = !!(((_a = userIdent === null || userIdent === void 0 ? void 0 : userIdent.managedIdentity) === null || _a === void 0 ? void 0 : _a.emailVerified) || ((_b = data === null || data === void 0 ? void 0 : data.verifyManagedIdentityEmail) === null || _b === void 0 ? void 0 : _b.success) ||
    successful);
  const validEmail = ((_c = userIdent === null || userIdent === void 0 ? void 0 : userIdent.managedIdentity) === null || _c === void 0 ? void 0 : _c.email) === oobEmail;
  const failed = () => {
    return navigation.push({
      pathname: failedPage,
      search: urlParams.toString() && "?" + urlParams.toString(),
    });
  };
  const gotoNextPage = () => {
    urlParams.delete("nextPage");
    const url = sanitizeUrlPath(nextPageOverride || nextPage);
    navigation.push(url.href);
  };
  const logout = () => {
    setTimeout(() => {
      setUserIdentity(undefined);
      gotoNextPage();
    }, 3000);
  };
  const login = () => {
    setTimeout(gotoNextPage, 3000);
  };
  useEffect(() => {
    const verify = async () => {
      if (!globalPromise)
        globalPromise = request({ oobCode });
      const result = await globalPromise;
      if (!(result instanceof Error) &&
        result.verifyManagedIdentityEmail.success) {
        // Needs to be explicitly updated if multiple renders have occured
        setSuccessful(true);
      }
      setCompleted(true);
    };
    verify();
  }, []);
  useEffect(() => {
    if (!completed)
      return;
    if (verified && validEmail)
      login();
    else
      logout();
  }, [completed, verified]);
  return {
    states: {
      loading: loading || !completed,
      disableContinue,
      error: ((_g = (_f = (_e = (_d = errors === null || errors === void 0 ? void 0 : errors.response) === null || _d === void 0 ? void 0 : _d.errors) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.extensions) === null || _g === void 0 ? void 0 : _g.message) || ((_k = (_j = (_h = errors === null || errors === void 0 ? void 0 : errors.response) === null || _h === void 0 ? void 0 : _h.errors) === null || _j === void 0 ? void 0 : _j[0]) === null || _k === void 0 ? void 0 : _k.message) ||
        (((errors === null || errors === void 0 ? void 0 : errors.message) || !validEmail) && networkErrorMessage),
      success: completed && successful && (verified || validEmail),
    },
    data: {
      oobCode,
    },
    callbacks: {
      failed,
      gotoNextPage,
    },
    content: {
      verifySuccessText,
      verifyEmailText,
      verifyInvalidText,
      continueText,
    },
  };
}
