import { navigation, useManagedIdentitySessionQuery, useRequestVerificationEmailMutation, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { useCallback, useEffect, useRef, useState, } from "@saasquatch/universal-hooks";
export function usePortalEmailVerification(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
  const [request, { loading, data, errors }] = useRequestVerificationEmailMutation();
  const [getVerificationStatus, { data: user, loading: loadingVerification }] = useManagedIdentitySessionQuery();
  const userIdent = useUserIdentity();
  const email = (_a = userIdent === null || userIdent === void 0 ? void 0 : userIdent.managedIdentity) === null || _a === void 0 ? void 0 : _a.email;
  const urlParams = new URLSearchParams(navigation.location.search);
  const nextPage = urlParams.get("nextPage");
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");
  const [countdown, setCountdown] = useState(10);
  const timerRef = useRef(undefined);
  const countdownRef = useRef(undefined);
  const submit = async () => {
    var _a;
    if (!email)
      return;
    setError("");
    setSuccess(false);
    const urlParams = nextPage ? { nextPage } : null;
    const redirectPath = props.redirectPath;
    const variables = { email, urlParams, redirectPath };
    const result = await request(variables);
    if (result instanceof Error) {
      if (result.message)
        setError(props.networkErrorMessage);
      return;
    }
    if ((_a = result.requestManagedIdentityVerificationEmail) === null || _a === void 0 ? void 0 : _a.success)
      setSuccess(true);
  };
  async function checkVerification() {
    var _a;
    const data = (await getVerificationStatus());
    if ((_a = data === null || data === void 0 ? void 0 : data.managedIdentitySession) === null || _a === void 0 ? void 0 : _a.emailVerified) {
      clearInterval(timerRef.current);
      return navigation.push({
        pathname: props.redirectPath,
        search: urlParams.toString() && "?" + urlParams.toString(),
      });
    }
    resyncTimers(10);
  }
  const startTimer = (countdown = 10000) => setInterval(checkVerification, countdown);
  const startCountdown = (countdown) => setInterval(() => setCountdown(countdown), 1000);
  function resyncTimers(restartCountdown) {
    // Clear existing timers
    clearInterval(countdownRef.current);
    clearInterval(timerRef.current);
    // Do nothing if the tab is currently hidden
    if (document.visibilityState === "hidden")
      return;
    // Restart the timer if verification has just been checked
    if (restartCountdown)
      setCountdown(restartCountdown);
    // Default back to 10 if the countdown got to zero
    let newCountdown = countdown || 10;
    // Start timers from either the beginning or based on the previous value
    countdownRef.current = startCountdown(restartCountdown - 1 || newCountdown - 1);
    timerRef.current = startTimer(restartCountdown * 1000 || newCountdown * 1000);
  }
  const resyncTimersCallback = useCallback(() => resyncTimers(), [countdown]);
  // Refetch validation status timer
  useEffect(() => {
    if (!timerRef.current) {
      checkVerification();
      timerRef.current = startTimer();
    }
    return () => {
      clearInterval(timerRef.current);
    };
  }, []);
  // Countdown timer
  useEffect(() => {
    if (countdown > 0) {
      clearInterval(countdownRef.current);
      countdownRef.current = startCountdown(countdown - 1);
    }
    // Re-sync the timers if tab visibility has changed
    document.addEventListener("visibilitychange", resyncTimersCallback);
    return () => {
      clearInterval(countdownRef.current);
      document.removeEventListener("visibilitychange", resyncTimersCallback);
    };
  }, [countdown]);
  return {
    states: {
      loading,
      error: ((_e = (_d = (_c = (_b = errors === null || errors === void 0 ? void 0 : errors.response) === null || _b === void 0 ? void 0 : _b.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.extensions) === null || _e === void 0 ? void 0 : _e.message) || ((_h = (_g = (_f = errors === null || errors === void 0 ? void 0 : errors.response) === null || _f === void 0 ? void 0 : _f.errors) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.message) ||
        error,
      success,
      loadingVerification,
      isVerified: !!((_j = user === null || user === void 0 ? void 0 : user.managedIdentitySession) === null || _j === void 0 ? void 0 : _j.emailVerified),
      countdown,
    },
    callbacks: {
      submit,
    },
    content: {
      email,
      verifyMessage: props.verifyMessage,
      emailVerificationHeader: props.emailVerificationHeader,
      resendEmailButtonText: props.resendEmailButtonText,
      verificationLoadingMessage: props.verificationLoadingMessage,
      verificationStatusMessage: props.verificationStatusMessage,
      verificationResentMessage: props.verificationResentMessage,
      networkErrorMessage: props.networkErrorMessage,
    },
  };
}
