import { useDispatch } from 'react-redux';
import Router from 'next/router';

import { REDIRECT_URL_STORAGE_NAME } from '@/modules/@common/storage/constants';
import { AUTH_TYPES } from '@/modules/auth/SsoLogin/constants';

import {
  getSessionStorageItem,
  getStorageItem,
  removeStorageItem,
  setBrowserStorageItem,
} from '@/modules/@common/storage/helpers';
import { getCustomLoginPageByAccountIdAction, getSsoLinkAction } from '@/modules/auth/Login/redux/slices';

const PARAMS = {
  account: 'acid',
  user: 'u',
  redirectUrl: 'olp',
};

/**
 * Background sso login redirect url storage manager
 */
const SSO_REDIRECT_URL_STORAGE_NAME = 'SSO_REDIRECT_URL_STORAGE_NAME';

const getSubdomain = () => {
  const subdomain = window.location.host.split('.')[0];
  const mainSubdomain = process.env.APP_ENV_BASE_URL.split('//')[1].split('.')[0];
  const isCustomSubdomain = subdomain !== mainSubdomain;

  return {
    subdomain,
    isCustomSubdomain,
  };
};

export const ssoRedirectUrlManager = {
  set: (link) => setBrowserStorageItem(SSO_REDIRECT_URL_STORAGE_NAME, link),
  get: () => getStorageItem(SSO_REDIRECT_URL_STORAGE_NAME) || '',
  clear: () => removeStorageItem(SSO_REDIRECT_URL_STORAGE_NAME),
};

/**
 * Cleanup history from url
 */
export const getFromUrlWithoutAccountUserParams = () => {
  const fromLocation = getSessionStorageItem(REDIRECT_URL_STORAGE_NAME);

  if (!fromLocation) return '/';

  const url = new URL(fromLocation);
  url.searchParams.delete(PARAMS.account);
  url.searchParams.delete(PARAMS.user);

  return url.toString();
};

function useSsoBackgroundLogin() {
  const dispatch = useDispatch();

  const ssoLoginByUParam = (u = null, ssoCheck = null) => {
    const params = Router.query;
    const email = u || params[PARAMS.user];

    const { subdomain, isCustomSubdomain } = getSubdomain();

    if (email || isCustomSubdomain) {
      dispatch(
        getSsoLinkAction({
          type: AUTH_TYPES.byEmail,
          email,
          subdomain: isCustomSubdomain ? subdomain : null,
          shouldRedirectToLoginPageIfError: true,
          ssoCheck,
        }),
      );
    }
  };

  const initSsoBackgroundLoginFlow = () => {
    const { isCustomSubdomain } = getSubdomain();

    try {
      const fromLocation = new URL(getSessionStorageItem(REDIRECT_URL_STORAGE_NAME));
      const params = new URLSearchParams(fromLocation.search);
      const redirectUrl = getFromUrlWithoutAccountUserParams();

      // save redirect url to localstorage
      ssoRedirectUrlManager.set(redirectUrl);

      if (params.get(PARAMS.user) || isCustomSubdomain) {
        ssoLoginByUParam(params.get(PARAMS.user));
      } else if (params.get(PARAMS.account)) {
        const accountId = params.get(PARAMS.account);

        dispatch(
          getCustomLoginPageByAccountIdAction({
            accountId,
            redirectUrl,
          }),
        );
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      if (isCustomSubdomain) {
        ssoLoginByUParam(null, true);
      }

      return false;
    }

    return false;
  };

  const getRedirectUrl = () => ssoRedirectUrlManager.get();

  return {
    initSsoBackgroundLoginFlow,
    getRedirectUrl,
    ssoLoginByUParam,
  };
}

export default useSsoBackgroundLogin;
