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 DiscountSimulator = lazy(() => import('./pages/DiscountSimulator'));
const HtsLookup = lazy(() => import('./pages/HtsLookup'));
const SpecLookup = lazy(() => import('./pages/SpecLookup'));
const Categories = lazy(() => import('./pages/Categories'));
const Brands = lazy(() => import('./pages/Brands'));
const ProductLines = lazy(() => import('./pages/ProductLines'));
const PurchaseOrders = lazy(() => import('./pages/PurchaseOrders'));
const CreatePurchaseOrder = lazy(() => import('./pages/CreatePurchaseOrder'));
const BlackFridayDashboard = lazy(() => import('./pages/BlackFridayDashboard'));
const Newsletter = lazy(() => import('./pages/Newsletter'));
const RepeatOrders = lazy(() => import('./pages/RepeatOrders'));

// 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 })));

// Product editor
const ProductEditor = lazy(() => import('./pages/ProductEditor'));

// Bulk edit
const BulkEdit = lazy(() => import('./pages/BulkEdit'));

// 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 */}
            {/* Default route now prioritizes dashboard, then other pages */}
            <Route index element={<FirstAccessiblePage />} />
            <Route path="/overview" element={
              <Protected page="overview">
                <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="/brands" element={
              <Protected page="brands">
                <Suspense fallback={<PageLoading />}>
                  <Brands />
                </Suspense>
              </Protected>
            } />
            <Route path="/product-lines" element={
              <Protected page="product_lines">
                <Suspense fallback={<PageLoading />}>
                  <ProductLines />
                </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="/discount-simulator" element={
              <Protected page="discount_simulator">
                <Suspense fallback={<PageLoading />}>
                  <DiscountSimulator />
                </Suspense>
              </Protected>
            } />
            <Route path="/hts-lookup" element={
              <Protected page="hts_lookup">
                <Suspense fallback={<PageLoading />}>
                  <HtsLookup />
                </Suspense>
              </Protected>
            } />
            <Route path="/spec-lookup" element={
              <Protected page="spec_lookup">
                <Suspense fallback={<PageLoading />}>
                  <SpecLookup />
                </Suspense>
              </Protected>
            } />
            <Route path="/forecasting" element={
              <Protected page="forecasting">
                <Suspense fallback={<PageLoading />}>
                  <Forecasting />
                </Suspense>
              </Protected>
            } />
            <Route path="/repeat-orders" element={
              <Protected page="repeat_orders">
                <Suspense fallback={<PageLoading />}>
                  <RepeatOrders />
                </Suspense>
              </Protected>
            } />
            <Route path="/create-purchase-order" element={
              <Protected page="create_purchase_orders">
                <Suspense fallback={<PageLoading />}>
                  <CreatePurchaseOrder />
                </Suspense>
              </Protected>
            } />
            
            {/* Always loaded settings */}
            <Route path="/settings" element={
              <Protected page="settings">
                <Settings />
              </Protected>
            } />
            
            {/* Product editor */}
            <Route path="/product-editor" element={
              <Protected page="product_editor">
                <Suspense fallback={<PageLoading />}>
                  <ProductEditor />
                </Suspense>
              </Protected>
            } />

            {/* Bulk edit */}
            <Route path="/bulk-edit" element={
              <Protected page="bulk_edit">
                <Suspense fallback={<PageLoading />}>
                  <BulkEdit />
                </Suspense>
              </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>
            } />
            
            {/* Newsletter recommendations */}
            <Route path="/newsletter" element={
              <Protected page="newsletter">
                <Suspense fallback={<PageLoading />}>
                  <Newsletter />
                </Suspense>
              </Protected>
            } />

            {/* Dashboard app - separate chunk */}
            <Route path="/dashboard" element={
              <Protected page="dashboard">
                <Suspense fallback={<PageLoading />}>
                  <Dashboard />
                </Suspense>
              </Protected>
            } />
            <Route path="/dashboard/black-friday" element={
              <Protected page="black_friday_dashboard">
                <Suspense fallback={<PageLoading />}>
                  <BlackFridayDashboard />
                </Suspense>
              </Protected>
            } />
            
            <Route path="*" element={<Navigate to="/" replace />} />
          </Route>
        </Routes>
      </AuthProvider>
    </QueryClientProvider>
  );
}

export default App;
