import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';

import { LOGIN_PAGE } from '@/modules/@common/router/constants';
import { REDIRECT_URL_STORAGE_NAME } from '@/modules/@common/storage/constants';

import { removeSessionStorageItem, setSessionStorageItem } from '@/modules/@common/storage/helpers';

const REDIRECT_QUERY_KEY = 'redirectTo=';

function getNormalizeRedirectUrl(redirectUrl) {
  let normalizeRedirectUrl = '';

  if (!redirectUrl) {
    return normalizeRedirectUrl;
  }

  try {
    const p = new URL(redirectUrl, window.location.origin);
    normalizeRedirectUrl = `${window.location.origin}${p.pathname}${p.search}${p.hash}`;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (e) {
    normalizeRedirectUrl = '';
  }

  return normalizeRedirectUrl;
}

function useSetRedirectUrl() {
  const [isRedirectUrlAdded, setIsRedirectUrlAdded] = useState(false);
  const router = useRouter();

  useEffect(() => {
    const redirectUrlObject = new URL(router.asPath, window.location.origin);

    let redirectUrl = getNormalizeRedirectUrl(redirectUrlObject.search.split(REDIRECT_QUERY_KEY)[1]);

    if (redirectUrl && redirectUrlObject.hash) {
      redirectUrl += redirectUrlObject.hash;
    }

    if (redirectUrl && redirectUrl.search('/login') === -1) {
      setSessionStorageItem(REDIRECT_URL_STORAGE_NAME, redirectUrl);
    } else {
      // to avoid infinite redirect to login
      removeSessionStorageItem(REDIRECT_URL_STORAGE_NAME);
    }

    setIsRedirectUrlAdded(true);

    router.replace(LOGIN_PAGE.path);
  }, []);

  return {
    isRedirectUrlAdded,
  };
}

export default useSetRedirectUrl;
