import { useEffect, useCallback } from 'react';

import { paths } from '@/routes/paths';
import { useRouter, useSearchParams } from '@/hooks';

import { SplashScreen } from '@/shared/components/loading-screen';
import { useAuthContext } from '@/hooks/use-auth-context';
import { getTokenInfo } from '@/utils/token';
import { useAuthStore } from '@/shared/api/stores/authStore';

// ----------------------------------------------------------------------

type Props = {
  children: React.ReactNode;
};

export default function GuestGuard({ children }: Props) {
  const { loading } = useAuthContext();

  return <>{loading ? <SplashScreen /> : <Container>{children}</Container>}</>;
}

// ----------------------------------------------------------------------

function Container({ children }: Props) {
  const router = useRouter();

  const searchParams = useSearchParams();
  const { logout } = useAuthStore();

  const returnTo = searchParams.get('returnTo') || paths.dashboard.root;
  const handleLogout = useCallback(async () => {
    await logout();
    const returnTo = encodeURIComponent(window.location.pathname);
    router.replace(`${paths.auth.jwt.login}?returnTo=${returnTo}`);
  }, [logout, router]);

  const check = useCallback(() => {
    const token = localStorage.getItem('token');

    if (token) {
      const tokenInfo = getTokenInfo(token);
      if (tokenInfo.isValid) {
        router.replace(returnTo);
      } else {
        handleLogout();
      }
    }else{
      handleLogout();
    }
  }, [returnTo, router]);

  useEffect(() => {
    check();
  }, [check]);

  return <>{children}</>;
}
