import {
  RouterProvider,
  createBrowserRouter,
  Navigate,
} from 'react-router-dom';
import { useEffect, useState } from 'react';
import Chat from './pages/Chat.tsx';
import Login from './pages/Login.tsx';
import Signup from './pages/Signup.tsx';
import Settings from './pages/Settings.tsx';
import Lost from './pages/404.tsx';
import { AuthContext } from './utils/AuthProvider.tsx';
import ProtectedRoutes from './utils/ProtectedRoutes.tsx';
import PublicRoute from '@/utils/PublicRoute.tsx';
import axios from 'axios';
import Cookies from 'js-cookie';
export const axiosClient = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});
const router = createBrowserRouter([
  {
    path: '/',
    element: <Navigate to="/chat" replace />,
  },
  {
    element: <ProtectedRoutes />,
    children: [
      {
        path: '/chat',
        element: <Chat />,
      },
      {
        path: '/settings',
        element: <Settings />,
      },
    ],
  },
  {
    element: <PublicRoute />,
    children: [
      {
        path: '/login',
        element: <Login />,
      },
      {
        path: '/signup',
        element: <Signup />,
      },
    ],
  },
  {
    path: '*',
    element: <Lost />,
  },
]);

function App() {
  const [authorized, setAuthorized] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

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

      try {
        await axiosClient.get('/api/auth/validate', {
          withCredentials: true,
        });
        setAuthorized(true);
      } catch (e) {
        setAuthorized(false);
        console.log('Failed to validate token: ', e);
      } finally {
        setIsLoading(false);
      }
    }

    validateToken();
  }, []);

  return (
    <AuthContext.Provider value={{ authorized, isLoading, setAuthorized }}>
      <RouterProvider router={router} />
    </AuthContext.Provider>
  );
}
export default App;
