import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { RoleProvider } from './contexts/RoleContext';
import { useEffect, Component, ErrorInfo, ReactNode, Suspense, lazy } from 'react';
import { initConnectionManager } from './lib/connectionManager';
import { useAnalytics } from './hooks/useAnalytics';
import { useServiceWorker } from './hooks/useServiceWorker';
import { performanceMonitor } from './lib/performanceMonitor';
import OfflineBanner from './components/OfflineBanner';
import LoadingState from './components/LoadingState';
import { Toaster } from 'react-hot-toast';
import AuthRoute from './components/AuthRoute';
import PageErrorBoundary from './components/PageErrorBoundary';
import Dashboard from './components/Dashboard';
import SkeletonLoader from './components/SkeletonLoader';
import './styles/printStyles.css';

// Lazy load pages for better code splitting and performance
const Sales = lazy(() => import('./pages/Sales'));
const ManagerDashboard = lazy(() => import('./pages/ManagerDashboard'));
const CashierDashboard = lazy(() => import('./pages/CashierDashboard'));
const SalespersonDashboard = lazy(() => import('./pages/SalespersonDashboard'));
const AdminDashboard = lazy(() => import('./pages/AdminDashboard'));
const SelectPlan = lazy(() => import('./pages/SelectPlan'));
const ContactAdmin = lazy(() => import('./pages/ContactAdmin'));
const SuperAdminDashboard = lazy(() => import('./pages/SuperAdminDashboard'));
const Login = lazy(() => import('./pages/Login'));
const LandingPage = lazy(() => import('./pages/LandingPage'));
const Checkout = lazy(() => import('./pages/Checkout'));
const Products = lazy(() => import('./pages/Products'));
const Purchase = lazy(() => import('./pages/Purchase'));
const Customers = lazy(() => import('./pages/Customers'));
const Reports = lazy(() => import('./pages/Reports'));
const GSTReports = lazy(() => import('./pages/GSTReports'));
const GSTSettings = lazy(() => import('./pages/GSTSettings'));
const WhatsAppSettings = lazy(() => import('./pages/WhatsAppSettings'));
const SalesReturn = lazy(() => import('./pages/SalesReturn'));
const OffersPromotions = lazy(() => import('./pages/OffersPromotions'));
const Users = lazy(() => import('./pages/Users'));
const Companies = lazy(() => import('./pages/Companies'));
const RoleSelection = lazy(() => import('./pages/RoleSelection'));
const AdminPanel = lazy(() => import('./pages/AdminPanel'));
const CompanyCreation = lazy(() => import('./pages/CompanyCreation'));
const SubscriptionBlocked = lazy(() => import('./pages/SubscriptionBlocked'));
const StockReport = lazy(() => import('./pages/StockReport'));
const ProfitLossReports = lazy(() => import('./pages/ProfitLossReports'));
const ExpensePage = lazy(() => import('./pages/ExpensePage'));
const ExpenseReportPage = lazy(() => import('./pages/ExpenseReportPage'));
const GrossProfitLossPage = lazy(() => import('./pages/GrossProfitLossPage'));
const TestPage = lazy(() => import('./pages/TestPage'));
const ProfessionalInvoiceDemo = lazy(() => import('./pages/ProfessionalInvoiceDemo'));
const BarcodePrinting = lazy(() => import('./pages/BarcodePrinting'));
const TestDashboard = lazy(() => import('./pages/TestDashboard'));
const UserProfile = lazy(() => import('./pages/UserProfile'));
const DatabaseTools = lazy(() => import('./pages/DatabaseTools'));
const AuditReportPage = lazy(() => import('./pages/AuditReportPage'));

// Loading fallback component for lazy-loaded routes - OPTIMIZED
const PageLoader = () => <SkeletonLoader variant="page" />;

class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null }> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-red-50 p-4">
          <div className="max-w-md w-full bg-white p-8 rounded-lg shadow-lg">
            <h2 className="text-2xl font-bold text-red-600 mb-4">Something went wrong</h2>
            <p className="text-gray-700 mb-4">
              We're sorry, but an error occurred while loading the application.
            </p>
            <details className="bg-gray-100 p-4 rounded mb-4">
              <summary className="font-semibold cursor-pointer">Error details</summary>
              <pre className="mt-2 text-sm text-red-500 whitespace-pre-wrap">
                {this.state.error?.toString()}
              </pre>
            </details>
            <button
              className="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded"
              onClick={() => window.location.reload()}
            >
              Reload Page
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

function App() {
  // Initialize analytics
  useAnalytics();
  
  // Initialize service worker for PWA
  const { isOnline } = useServiceWorker();
  
  // Initialize performance monitoring
  useEffect(() => {
    // Performance monitor auto-initializes on import
    // but we can manually trigger logging if needed
    if (import.meta.env.DEV) {
      setTimeout(() => {
        const metrics = performanceMonitor.getMetrics();
        if (metrics.loadTime) {
          console.log('🚀 App loaded in', metrics.loadTime.toFixed(0), 'ms');
        }
      }, 3000);
    }
  }, []);
  
  // Add global error handler to catch "undefined is not iterable" errors
  useEffect(() => {
    const handleError = (event: ErrorEvent) => {
      console.error('🚨 Global error caught:', event.error);
      console.error('🚨 Error stack:', event.error?.stack);
      
      if (event.error?.message?.includes('undefined is not iterable')) {
        console.error('🔍 Found the "undefined is not iterable" error!');
        console.error('🔍 Error details:', {
          message: event.error.message,
          stack: event.error.stack
        });
      }
    };

    window.addEventListener('error', handleError);
    
    // Also handle unhandled promise rejections
    const handleRejection = (event: PromiseRejectionEvent) => {
      console.error('🚨 Unhandled promise rejection:', event.reason);
      
      if (event.reason?.message?.includes('undefined is not iterable')) {
        console.error('🔍 Found "undefined is not iterable" in promise rejection!');
        console.error('🔍 Rejection details:', {
          reason: event.reason,
          stack: event.reason?.stack
        });
      }
    };

    window.addEventListener('unhandledrejection', handleRejection);

    return () => {
      window.removeEventListener('error', handleError);
      window.removeEventListener('unhandledrejection', handleRejection);
    };
  }, []);

  // Initialize connection manager when the app loads
  useEffect(() => {
    // Initialize the unified connection manager
    const connectionCleanup = initConnectionManager();
    
    // Cleanup on unmount
    return () => {
      connectionCleanup();
    };
  }, []);

  return (
    <>
      {/* Offline Banner for PWA */}
      <OfflineBanner isOnline={isOnline} />
      
      <Toaster 
        position="top-center" 
        toastOptions={{ 
          duration: 6000, 
          style: { 
            background: '#333', 
            color: '#fff', 
            padding: '16px', 
            borderRadius: '8px', 
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)', 
            zIndex: 9999 
          } 
        }} 
      />
      <Router future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        <ErrorBoundary>
          <RoleProvider>
            {/* Accessibility: Main content wrapper */}
            <main id="main-content" role="main" tabIndex={-1}>
              <Routes>
              {/* Public routes - accessible without auth */}
              <Route path="/" element={<Suspense fallback={<PageLoader />}><LandingPage /></Suspense>} />
              <Route path="/landing" element={<Suspense fallback={<PageLoader />}><LandingPage /></Suspense>} /> {/* Debug route to force landing page */}
              <Route path="/login" element={<Suspense fallback={<PageLoader />}><Login /></Suspense>} />
              <Route path="/signup" element={<Suspense fallback={<PageLoader />}><Login /></Suspense>} />
              <Route path="/checkout" element={<Suspense fallback={<PageLoader />}><Checkout /></Suspense>} />
              <Route path="/test-login" element={<Suspense fallback={<PageLoader />}><TestDashboard /></Suspense>} />
              <Route path="/select-plan" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <SelectPlan />
                  </AuthRoute>
                </Suspense>
              } />
              
              <Route path="/contact-admin" element={<Suspense fallback={<PageLoader />}><ContactAdmin /></Suspense>} />
              <Route path="/role-selection" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute redirectTo="/signup">
                    <RoleSelection />
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/test" element={<Suspense fallback={<PageLoader />}><TestPage /></Suspense>} />
              <Route path="/admin" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <AdminPanel />
                  </AuthRoute>
                </Suspense>
              } />

              {/* Role-specific dashboard routes */}
              <Route path="/super-admin-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Super Admin Dashboard">
                      <SuperAdminDashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />

              <Route path="/create-company" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Create Company">
                      <CompanyCreation />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/subscription-blocked" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Subscription Blocked">
                      <SubscriptionBlocked />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/admin-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole="admin">
                    <PageErrorBoundary pageName="Admin Dashboard">
                      <AdminDashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/manager-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Manager Dashboard">
                      <ManagerDashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/cashier-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Cashier Dashboard">
                      <CashierDashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/salesperson-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Salesperson Dashboard">
                      <SalespersonDashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              
              {/* Feature routes */}
              <Route path="/products" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Products">
                      <Products />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Dashboard">
                      <Dashboard />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/barcode-printing" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Barcode Printing">
                      <BarcodePrinting />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/sales" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Sales">
                      <Sales />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/sales-return" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Sales Return">
                      <SalesReturn />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/offers-promotions" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Offers & Promotions">
                      <OffersPromotions />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/purchase" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Purchase">
                      <Purchase />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/customers" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Customers">
                      <Customers />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/reports" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Reports">
                      <Reports />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/gst-reports" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="GST Reports">
                      <GSTReports />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/gst-settings" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "owner", "manager"]}>
                    <PageErrorBoundary pageName="GST Settings">
                      <GSTSettings />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/whatsapp-settings" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="WhatsApp Settings">
                      <WhatsAppSettings />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/users" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole="admin" noLayout={true}>
                    <PageErrorBoundary pageName="Users">
                      <Users />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/companies" element={<Suspense fallback={<PageLoader />}><Companies /></Suspense>} />
              <Route path="/companies/:id" element={<Suspense fallback={<PageLoader />}><Companies /></Suspense>} />
              <Route path="/settings" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "owner", "manager"]}>
                    <PageErrorBoundary pageName="Settings">
                      <GSTSettings />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/profile" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute noLayout={true}>
                    <PageErrorBoundary pageName="User Profile">
                      <UserProfile />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/database" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "owner"]}>
                    <PageErrorBoundary pageName="Database Tools">
                      <DatabaseTools />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/stock-report" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <PageErrorBoundary pageName="Stock Report">
                      <StockReport />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/profit-loss-reports" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="Profit & Loss Reports">
                      <ProfitLossReports />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              
              {/* New expense routes */}
              <Route path="/expenses/add" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="Add Expense">
                      <ExpensePage />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/expenses/reports" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="Expense Reports">
                      <ExpenseReportPage />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/profit-loss" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="Gross Profit & Loss">
                      <GrossProfitLossPage />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              <Route path="/audit-report" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole={["admin", "manager", "owner"]}>
                    <PageErrorBoundary pageName="Audit Report">
                      <AuditReportPage />
                    </PageErrorBoundary>
                  </AuthRoute>
                </Suspense>
              } />
              
              {/* Professional Invoice Demo Route */}
              <Route path="/professional-invoice-demo" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute requiredRole="admin">
                    <ProfessionalInvoiceDemo />
                  </AuthRoute>
                </Suspense>
              } />
              
              {/* Redirect unknown routes to dashboard */}
              <Route path="/*" element={
                <Suspense fallback={<PageLoader />}>
                  <Navigate to="/dashboard" replace />
                </Suspense>
              } />
              
              {/* Debug route - bypass all checks */}
              <Route path="/debug-dashboard" element={
                <Suspense fallback={<PageLoader />}>
                  <AuthRoute>
                    <TestDashboard />
                  </AuthRoute>
                </Suspense>
              } />
            </Routes>
            </main>
          </RoleProvider>
        </ErrorBoundary>
      </Router>
    </>
  );
}

export default App;