import { Routes, Route, useNavigate, Navigate, useLocation } from 'react-router-dom';
import { MainLayout } from './components/layout/MainLayout';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from '@/components/ui/sonner';
import { useEffect, Suspense, lazy } from 'react';
import config from './config';
import { RequireAuth } from './components/auth/RequireAuth';
import { AuthProvider } from './contexts/AuthContext';
import { Protected } from './components/auth/Protected';
import { FirstAccessiblePage } from './components/auth/FirstAccessiblePage';
import { PageLoading } from '@/components/ui/page-loading';

// Always loaded components (Login and Settings stay in main bundle)
import { Settings } from './pages/Settings';  
import { Login } from './pages/Login';

// Lazy load the 4 main chunks you wanted:

// 1. Core inventory app - loaded as one chunk when any inventory page is accessed
const Overview = lazy(() => import('./pages/Overview'));
const Products = lazy(() => import('./pages/Products').then(module => ({ default: module.Products })));
const Analytics = lazy(() => import('./pages/Analytics').then(module => ({ default: module.Analytics })));
const Forecasting = lazy(() => import('./pages/Forecasting'));
const Vendors = lazy(() => import('./pages/Vendors'));
const Categories = lazy(() => import('./pages/Categories'));  
const Brands = lazy(() => import('./pages/Brands'));
const PurchaseOrders = lazy(() => import('./pages/PurchaseOrders'));

// 2. Dashboard app - separate chunk
const Dashboard = lazy(() => import('./pages/Dashboard'));
const SmallDashboard = lazy(() => import('./pages/SmallDashboard'));

// 3. Product import - separate chunk  
const Import = lazy(() => import('./pages/Import').then(module => ({ default: module.Import })));

// 4. Chat archive - separate chunk
const Chat = lazy(() => import('./pages/Chat').then(module => ({ default: module.Chat })));

const queryClient = new QueryClient();

function App() {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true';
      
      // If we have a token but aren't logged in yet, verify the token
      if (token && !isLoggedIn) {
        try {
          const response = await fetch(`${config.authUrl}/me`, {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });
          
          if (!response.ok) {
            localStorage.removeItem('token');
            sessionStorage.removeItem('isLoggedIn');
            
            // Only navigate to login if we're not already there
            if (!location.pathname.includes('/login')) {
              navigate(`/login?redirect=${encodeURIComponent(location.pathname + location.search)}`);
            }
          } else {
            // If token is valid, set the login flag
            sessionStorage.setItem('isLoggedIn', 'true');
          }
        } catch (error) {
          console.error('Token verification failed:', error);
          localStorage.removeItem('token');
          sessionStorage.removeItem('isLoggedIn');
          
          // Only navigate to login if we're not already there
          if (!location.pathname.includes('/login')) {
            navigate(`/login?redirect=${encodeURIComponent(location.pathname + location.search)}`);
          }
        }
      }
    };

    checkAuth();
  }, [navigate, location.pathname, location.search]);

  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <Toaster richColors position="top-center" />
        <Routes>
          {/* Always loaded routes */}
          <Route path="/login" element={<Login />} />
          <Route path="/small" element={
            <Suspense fallback={<PageLoading />}>
              <SmallDashboard />
            </Suspense>
          } />
          <Route element={
            <RequireAuth>
              <MainLayout />
            </RequireAuth>
          }>
            {/* Core inventory app routes - will be lazy loaded */}
            <Route index element={
              <Protected page="overview" fallback={<FirstAccessiblePage />}>
                <Suspense fallback={<PageLoading />}>
                  <Overview />
                </Suspense>
              </Protected>
            } />
            <Route path="/products" element={
              <Protected page="products">
                <Suspense fallback={<PageLoading />}>
                  <Products />
                </Suspense>
              </Protected>
            } />
            <Route path="/categories" element={
              <Protected page="categories">
                <Suspense fallback={<PageLoading />}>
                  <Categories />
                </Suspense>
              </Protected>
            } />
            <Route path="/vendors" element={
              <Protected page="vendors">
                <Suspense fallback={<PageLoading />}>
                  <Vendors />
                </Suspense>
              </Protected>
            } />
            <Route path="/brands" element={
              <Protected page="brands">
                <Suspense fallback={<PageLoading />}>
                  <Brands />
                </Suspense>
              </Protected>
            } />
            <Route path="/purchase-orders" element={
              <Protected page="purchase_orders">
                <Suspense fallback={<PageLoading />}>
                  <PurchaseOrders />
                </Suspense>
              </Protected>
            } />
            <Route path="/analytics" element={
              <Protected page="analytics">
                <Suspense fallback={<PageLoading />}>
                  <Analytics />
                </Suspense>
              </Protected>
            } />
            <Route path="/forecasting" element={
              <Protected page="forecasting">
                <Suspense fallback={<PageLoading />}>
                  <Forecasting />
                </Suspense>
              </Protected>
            } />
            
            {/* Always loaded settings */}
            <Route path="/settings" element={
              <Protected page="settings">
                <Settings />
              </Protected>
            } />
            
            {/* Product import - separate chunk */}
            <Route path="/import" element={
              <Protected page="import">
                <Suspense fallback={<PageLoading />}>
                  <Import />
                </Suspense>
              </Protected>
            } />
            
            {/* Chat archive - separate chunk */}
            <Route path="/chat" element={
              <Protected page="chat">
                <Suspense fallback={<PageLoading />}>
                  <Chat />
                </Suspense>
              </Protected>
            } />
            
            {/* Dashboard app - separate chunk */}
            <Route path="/dashboard" element={
              <Protected page="dashboard">
                <Suspense fallback={<PageLoading />}>
                  <Dashboard />
                </Suspense>
              </Protected>
            } />
            
            <Route path="*" element={<Navigate to="/" replace />} />
          </Route>
        </Routes>
      </AuthProvider>
    </QueryClientProvider>
  );
}

export default App;

