import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { MainLayout } from './components/layout';
import { ToastContainer } from './components/ui';
import { useAuthStore } from './store/authStore';

// Lazy load pages for code splitting
const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login })));
const Register = lazy(() => import('./pages/Register').then(m => ({ default: m.Register })));
const Dashboard = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })));
const UsersPage = lazy(() => import('./pages/Users').then(m => ({ default: m.UsersPage })));
const ServiceOrdersPage = lazy(() => import('./pages/ServiceOrders').then(m => ({ default: m.ServiceOrdersPage })));
const ServiceOrdersKanbanPage = lazy(() => import('./pages/ServiceOrdersKanban').then(m => ({ default: m.ServiceOrdersKanbanPage })));
const ServiceOrderNewPage = lazy(() => import('./pages/ServiceOrderNew').then(m => ({ default: m.ServiceOrderNewPage })));
const ServiceOrderDetailPage = lazy(() => import('./pages/ServiceOrderDetail').then(m => ({ default: m.ServiceOrderDetailPage })));
const VehiclesPage = lazy(() => import('./pages/Vehicles').then(m => ({ default: m.VehiclesPage })));
const VehicleDetailPage = lazy(() => import('./pages/VehicleDetail').then(m => ({ default: m.VehicleDetailPage })));
const InventoryPage = lazy(() => import('./pages/Inventory').then(m => ({ default: m.InventoryPage })));
const InventoryDetailPage = lazy(() => import('./pages/InventoryDetail').then(m => ({ default: m.InventoryDetailPage })));
const CustomersPage = lazy(() => import('./pages/Customers').then(m => ({ default: m.CustomersPage })));
const CustomerDetailPage = lazy(() => import('./pages/CustomerDetail').then(m => ({ default: m.CustomerDetailPage })));
const QuotesPage = lazy(() => import('./pages/Quotes').then(m => ({ default: m.QuotesPage })));
const QuoteDetailPage = lazy(() => import('./pages/QuoteDetail').then(m => ({ default: m.QuoteDetailPage })));
const SettingsPage = lazy(() => import('./pages/Settings').then(m => ({ default: m.SettingsPage })));
const DiagnosticsPage = lazy(() => import('./pages/Diagnostics').then(m => ({ default: m.DiagnosticsPage })));
const DiagnosticsNewPage = lazy(() => import('./pages/DiagnosticsNew').then(m => ({ default: m.DiagnosticsNewPage })));
const DiagnosticDetailPage = lazy(() => import('./pages/DiagnosticDetail').then(m => ({ default: m.DiagnosticDetailPage })));

// Loading fallback component
function PageLoader() {
  return (
    <div className="flex h-64 items-center justify-center">
      <Loader2 className="h-8 w-8 animate-spin text-diesel-600" />
    </div>
  );
}

// Create React Query client
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      retry: 1,
    },
  },
});

// Protected route wrapper
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuthStore();

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
}

// Public route wrapper (redirect if already authenticated)
function PublicRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuthStore();

  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  return <>{children}</>;
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter>
        <Suspense fallback={<PageLoader />}>
          <Routes>
            {/* Public routes */}
            <Route path="/login" element={<PublicRoute><Login /></PublicRoute>} />
            <Route path="/register" element={<PublicRoute><Register /></PublicRoute>} />

            {/* Protected routes */}
            <Route
              path="/"
              element={
                <ProtectedRoute>
                  <MainLayout />
                </ProtectedRoute>
              }
            >
              <Route index element={<Navigate to="/dashboard" replace />} />
              <Route path="dashboard" element={<Dashboard />} />
              <Route path="orders" element={<ServiceOrdersPage />} />
              <Route path="orders/kanban" element={<ServiceOrdersKanbanPage />} />
              <Route path="orders/new" element={<ServiceOrderNewPage />} />
              <Route path="orders/:id" element={<ServiceOrderDetailPage />} />
              <Route path="diagnostics" element={<DiagnosticsPage />} />
              <Route path="diagnostics/new" element={<DiagnosticsNewPage />} />
              <Route path="diagnostics/:id" element={<DiagnosticDetailPage />} />
              <Route path="inventory" element={<InventoryPage />} />
              <Route path="inventory/:id" element={<InventoryDetailPage />} />
              <Route path="vehicles" element={<VehiclesPage />} />
              <Route path="vehicles/:id" element={<VehicleDetailPage />} />
              <Route path="customers" element={<CustomersPage />} />
              <Route path="customers/:id" element={<CustomerDetailPage />} />
              <Route path="quotes" element={<QuotesPage />} />
              <Route path="quotes/:id" element={<QuoteDetailPage />} />
              <Route path="users" element={<UsersPage />} />
              <Route path="settings" element={<SettingsPage />} />
            </Route>

            {/* 404 */}
            <Route
              path="*"
              element={
                <div className="flex h-screen items-center justify-center">
                  <div className="text-center">
                    <h1 className="text-4xl font-bold text-gray-900">404</h1>
                    <p className="text-gray-500">Pagina no encontrada</p>
                  </div>
                </div>
              }
            />
          </Routes>
        </Suspense>
        <ToastContainer />
      </BrowserRouter>
    </QueryClientProvider>
  );
}

export default App;
