import { Navigate, Outlet } from 'react-router-dom';
import { useState, useEffect, useContext } from 'react';
import { AuthContext } from './AuthProvider.tsx';
import LoadingScreen from '../components/LoadingScreen.tsx';
import { axiosClient } from '../App.tsx';

export type UsernameType = {
  username: string | null;
  user_id: string | null;
};

function ProtectedRoutes() {
  const { authorized, isLoading } = useContext(AuthContext);
  const [user, setUser] = useState<UsernameType>({
    username: null,
    user_id: null,
  });

  useEffect(() => {
    if (authorized) {
      axiosClient
        .get('/api/auth/validate', { withCredentials: true })
        .then((res) => {
          setUser(res.data);
        })
        .catch(console.error);
    }
  }, [authorized]);

  if (isLoading) {
    return <LoadingScreen />;
  }

  return authorized ? (
    <Outlet context={user satisfies UsernameType} />
  ) : (
    <Navigate to="/login" replace />
  );
}

export default ProtectedRoutes;
