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

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

function ProtectedRoutes() {
  const { authorized, setAuthorized } = useContext(AuthContext);
  const [username, setUsername] = useState<string | null>(null);

  useEffect(() => {
    function validateToken() {
      const token = Cookie.get('token');
      if (!token) {
        setAuthorized(false);
        return;
      }

      axiosClient
        .get('/api/auth/validate', { withCredentials: true })
        .then(async (res) => {
          setUsername(res.data.username);
          console.log(res.data.username);
          setAuthorized(true);
        })
        .catch((err) => {
          setAuthorized(false);
          console.log(err);
          console.log('Unauthorized');
        });
    }
    validateToken();
  }, [setAuthorized]);

  if (authorized === null) {
    return <LoadingScreen />;
  }

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

export default ProtectedRoutes;
