import { createFileRoute, Outlet, redirect, useNavigate } from '@tanstack/react-router';
import { AuthLayout } from '@/modules/auth/layouts/auth-layout';
import { DEFAULT_LOGGED_IN_ROUTE } from '@/lib/routes';
import { useAtomValue } from 'jotai';
import { authTokenAtom } from '@/modules/auth/hooks/use-auth-hook';
import { useEffect } from 'react';

export const Route = createFileRoute('/auth')({
  component: RouteComponent,
  beforeLoad: ({ context }) => {
    if (context.token) {
      throw redirect({
        to: DEFAULT_LOGGED_IN_ROUTE,
      });
    }
  },
});

function RouteComponent() {
  const token = useAtomValue(authTokenAtom);
  const navigate = useNavigate();

  // Navigate after successful authentication
  useEffect(() => {
    if (token) {
      navigate({ to: DEFAULT_LOGGED_IN_ROUTE, replace: true });
    }
  }, [token, navigate]);

  return (
    <AuthLayout>
      <Outlet />
    </AuthLayout>
  );
}
