import React, { Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import './App.css';

// Auth Provider
import { AuthProvider, useAuth } from './hooks/useAuth';

// Core components (loaded immediately)
import Header from './components/common/Header';
import Navigation from './components/common/Navigation';
import LoadingSpinner from './components/common/LoadingSpinner';
import Login from './components/auth/Login';
import ProtectedRoute from './components/auth/ProtectedRoute';

// Enhanced lazy loading with error boundaries and retry logic
import { 
  lazyLoadComponent, 
  preloadComponent, 
  preloadComponents,
  intelligentPreload 
} from './utils/lazyLoad';

// Lazy loaded components with optimized loading messages
const Dashboard = lazyLoadComponent(() => import('./components/common/Dashboard'), {
  cacheKey: 'dashboard',
  fallback: <LoadingSpinner message="Cargando dashboard..." />
});

const UserManagement = lazyLoadComponent(() => import('./components/auth/UserManagement'), {
  cacheKey: 'user-management',
  fallback: <LoadingSpinner message="Cargando gestión de usuarios..." />
});

const ProjectList = lazyLoadComponent(() => import('./components/projects/ProjectList'), {
  cacheKey: 'project-list',
  fallback: <LoadingSpinner message="Cargando proyectos..." />
});

const ProjectForm = lazyLoadComponent(() => import('./components/projects/ProjectForm'), {
  cacheKey: 'project-form',
  fallback: <LoadingSpinner message="Cargando formulario..." />
});

const RodalesManager = lazyLoadComponent(() => import('./components/rodales/RodalesManager'), {
  cacheKey: 'rodales-manager',
  fallback: <LoadingSpinner message="Cargando rodales..." />
});

const FieldApp = lazyLoadComponent(() => import('./components/field/FieldApp'), {
  cacheKey: 'field-app',
  fallback: <LoadingSpinner message="Cargando aplicación de campo..." />
});

const ReportDashboard = lazyLoadComponent(() => import('./components/reports/ReportDashboard'), {
  cacheKey: 'report-dashboard',
  fallback: <LoadingSpinner message="Cargando reportes..." />
});

// Test components (lazy loaded) - only in development
const FieldValidationTest = process.env.NODE_ENV === 'development' 
  ? lazyLoadComponent(() => import('./components/field/FieldValidationTest'), {
      cacheKey: 'field-validation-test',
      fallback: <LoadingSpinner message="Cargando test..." />
    })
  : null;

const TreeFormTest = process.env.NODE_ENV === 'development'
  ? lazyLoadComponent(() => import('./components/field/TreeFormTest'), {
      cacheKey: 'tree-form-test',
      fallback: <LoadingSpinner message="Cargando test..." />
    })
  : null;

const OfflineStorageTest = process.env.NODE_ENV === 'development'
  ? lazyLoadComponent(() => import('./components/common/OfflineStorageTest'), {
      cacheKey: 'offline-storage-test',
      fallback: <LoadingSpinner message="Cargando test..." />
    })
  : null;

const ServiceWorkerTest = process.env.NODE_ENV === 'development'
  ? lazyLoadComponent(() => import('./components/common/ServiceWorkerTest'), {
      cacheKey: 'service-worker-test',
      fallback: <LoadingSpinner message="Cargando test..." />
    })
  : null;

// Intelligent preloading based on user role and usage patterns
if (typeof window !== 'undefined') {
  // Preload critical components immediately
  const criticalComponents = [
    () => import('./components/common/Dashboard'),
    () => import('./components/field/FieldApp')
  ];
  
  // Preload critical components in parallel after initial render
  setTimeout(() => {
    preloadComponents(criticalComponents);
  }, 1000);
  
  // Role-based preloading
  const roleBasedPreload = (userRole) => {
    const roleComponents = {
      'Administrador': [
        () => import('./components/auth/UserManagement'),
        () => import('./components/projects/ProjectList'),
        () => import('./components/reports/ReportDashboard')
      ],
      'Regente': [
        () => import('./components/projects/ProjectList'),
        () => import('./components/projects/ProjectForm'),
        () => import('./components/reports/ReportDashboard')
      ],
      'Técnico de Campo': [
        () => import('./components/field/FieldApp'),
        () => import('./components/rodales/RodalesManager')
      ]
    };
    
    const components = roleComponents[userRole] || [];
    if (components.length > 0) {
      setTimeout(() => {
        preloadComponents(components);
      }, 2000);
    }
  };
  
  // Export for use in auth hook
  window.roleBasedPreload = roleBasedPreload;
}

// Main App Content Component
function AppContent() {
  const { user, loading } = useAuth();

  if (loading) {
    return <LoadingSpinner message="Cargando aplicación..." />;
  }

  return (
    <div className="App">
      {user && <Header user={user} />}
      {user && <Navigation userRole={user?.rol} />}
      
      <main className="main-content">
        <Routes>
          {/* Public routes */}
          <Route 
            path="/login" 
            element={!user ? <Login /> : <Navigate to="/" replace />} 
          />
          
          {/* Protected routes */}
          <Route 
            path="/" 
            element={
              <ProtectedRoute>
                <Suspense fallback={<LoadingSpinner message="Cargando dashboard..." />}>
                  <Dashboard user={user} />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Admin routes */}
          <Route 
            path="/users" 
            element={
              <ProtectedRoute requiredRoles={['Administrador']}>
                <Suspense fallback={<LoadingSpinner message="Cargando gestión de usuarios..." />}>
                  <UserManagement />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Project routes */}
          <Route 
            path="/projects" 
            element={
              <ProtectedRoute requiredRoles={['Administrador', 'Regente']}>
                <Suspense fallback={<LoadingSpinner message="Cargando proyectos..." />}>
                  <ProjectList />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          <Route 
            path="/projects/new" 
            element={
              <ProtectedRoute requiredRoles={['Administrador', 'Regente']}>
                <Suspense fallback={<LoadingSpinner message="Cargando formulario..." />}>
                  <ProjectForm />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Rodales routes */}
          <Route 
            path="/projects/:projectId/rodales" 
            element={
              <ProtectedRoute requiredRoles={['Administrador', 'Regente', 'Técnico de Campo']}>
                <Suspense fallback={<LoadingSpinner message="Cargando rodales..." />}>
                  <RodalesManager />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Field work route */}
          <Route 
            path="/field" 
            element={
              <ProtectedRoute requiredRoles={['Administrador', 'Regente', 'Técnico de Campo']}>
                <Suspense fallback={<LoadingSpinner message="Cargando aplicación de campo..." />}>
                  <FieldApp />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Reports route */}
          <Route 
            path="/reports" 
            element={
              <ProtectedRoute requiredRoles={['Administrador', 'Regente']}>
                <Suspense fallback={<LoadingSpinner message="Cargando reportes..." />}>
                  <ReportDashboard />
                </Suspense>
              </ProtectedRoute>
            } 
          />
          
          {/* Test routes - only in development */}
          {process.env.NODE_ENV === 'development' && (
            <>
              <Route 
                path="/test/field-validation" 
                element={
                  <ProtectedRoute>
                    <Suspense fallback={<LoadingSpinner message="Cargando test..." />}>
                      <FieldValidationTest />
                    </Suspense>
                  </ProtectedRoute>
                } 
              />
              <Route 
                path="/test/tree-form" 
                element={
                  <ProtectedRoute>
                    <Suspense fallback={<LoadingSpinner message="Cargando test..." />}>
                      <TreeFormTest />
                    </Suspense>
                  </ProtectedRoute>
                } 
              />
              <Route 
                path="/test/offline-storage" 
                element={
                  <ProtectedRoute>
                    <Suspense fallback={<LoadingSpinner message="Cargando test..." />}>
                      <OfflineStorageTest />
                    </Suspense>
                  </ProtectedRoute>
                } 
              />
              <Route 
                path="/test/service-worker" 
                element={
                  <ProtectedRoute requiredRoles={['Administrador']}>
                    <Suspense fallback={<LoadingSpinner message="Cargando test..." />}>
                      <ServiceWorkerTest />
                    </Suspense>
                  </ProtectedRoute>
                } 
              />
            </>
          )}
          
          {/* Catch all route */}
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </main>
    </div>
  );
}

// Main App Component with Auth Provider
function App() {
  return (
    <AuthProvider>
      <Router>
        <AppContent />
      </Router>
    </AuthProvider>
  );
}

export default App;