import React, { useCallback, useEffect } from 'react';
import { useAuth } from 'hooks';
import { SafeScreen } from 'components';
import { useLocation, useNavigate } from 'react-router-dom';
import { PATH_DASHBOARD } from 'navigation/web';
import { isLoggedInVar } from 'state-management/session';
import { useReactiveVar } from '@apollo/client';
import { getAccessToken, getPreRequestedRoute, getRefreshToken } from 'utils/auth';

export const Landing: React.FC = () => {
  const isLoggedIn = useReactiveVar(isLoggedInVar);

  const navigate = useNavigate();
  const { search } = useLocation();
  const { setAuthKeys, login } = useAuth();
  const routeQuery = new URLSearchParams(search);

  const accessToken = routeQuery?.get('accessToken');
  const refreshToken = routeQuery?.get('refreshToken');

  const setKeys = useCallback(async () => {
    setAuthKeys(accessToken as string, refreshToken as string);
  }, [accessToken, refreshToken, setAuthKeys]);

  const isCheckForLogin = useCallback(async () => {
    const accessTokenLocal = await getAccessToken();
    const refreshTokenLocal = await getRefreshToken();
    if (!accessTokenLocal && !refreshTokenLocal) {
      login();
    }
  }, [login]);

  const navigateAfterAuth = useCallback(async () => {
    const preRequested = await getPreRequestedRoute();
    if (preRequested) {
      window.location.href = preRequested;
    } else {
      navigate(PATH_DASHBOARD.root);
    }
  }, [navigate]);

  useEffect(() => {
    if (accessToken && refreshToken) {
      setKeys();
      navigateAfterAuth();
    }
  }, [accessToken, navigate, navigateAfterAuth, refreshToken, setKeys]);
  useEffect(() => {
    if (isLoggedIn) {
      navigateAfterAuth();
    } else {
      isCheckForLogin();
    }
  }, [
    accessToken,
    login,
    isLoggedIn,
    refreshToken,
    setAuthKeys,
    setKeys,
    navigate,
    isCheckForLogin,
    navigateAfterAuth,
  ]);
  return <SafeScreen />;
};
