import * as React from "react";
import { Switch, Route, useLocation } from "wouter";
import { useEffect } from "react";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Navigation } from "@/components/layout/navigation";
import { AuthProvider, useAuth } from "@/contexts/AuthContext";
import { ErrorBoundary } from "@/components/ErrorBoundary";

// Import pages
import Landing from "@/pages/landing";
import Login from "@/pages/login";
import Register from "@/pages/register";
import ClientDashboard from "@/pages/client-dashboard";
import PharmacyDashboard from "@/pages/pharmacy-dashboard";
import CourierDashboard from "@/pages/courier-dashboard";
import AdminDashboard from "@/pages/admin-dashboard";
import OrderTracking from "@/pages/order-tracking";
import NotFound from "@/pages/not-found";

function Router() {
  const { user, isLoading, isAuthenticated } = useAuth();
  const [location, setLocation] = useLocation();

  // Auto-redirect authenticated users to their dashboard from root
  useEffect(() => {
    if (!isLoading && isAuthenticated && user && location === '/') {
      const roleRoutes = {
        'client': '/client',
        'pharmacy': '/pharmacy', 
        'courier': '/courier',
        'admin': '/admin'
      };
      const userRole = user?.role || (user as any)?.user?.role;
      const targetRoute = roleRoutes[userRole as keyof typeof roleRoutes];
      if (targetRoute) {
        setLocation(targetRoute);
      }
    }
  }, [isLoading, isAuthenticated, user, location, setLocation]);

  // Show loading spinner while checking authentication
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">Vérification de l'authentification...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <Navigation userRole={user?.role || (user as any)?.user?.role || 'guest'} />
      <main className="min-h-screen">
        <Switch>
          <Route path="/" component={Landing} />
          
          {/* Auth pages */}
          <Route path="/login" component={Login} />
          <Route path="/register" component={Register} />
          
          {/* Protected routes - redirect to login if not authenticated */}
          <Route path="/client">
            {isAuthenticated ? <ClientDashboard /> : <Login />}
          </Route>
          <Route path="/pharmacy">
            {isAuthenticated ? <PharmacyDashboard /> : <Login />}
          </Route>
          <Route path="/courier">
            {isAuthenticated ? <CourierDashboard /> : <Login />}
          </Route>
          <Route path="/admin">
            {isAuthenticated ? <AdminDashboard /> : <Login />}
          </Route>
          <Route path="/tracking/:orderId?" component={OrderTracking} />
          
          <Route component={NotFound} />
        </Switch>
      </main>
    </>
  );
}

function AppContent() {
  return (
    <TooltipProvider>
      <Toaster />
      <Router />
    </TooltipProvider>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <AuthProvider>
          <AppContent />
        </AuthProvider>
      </QueryClientProvider>
    </ErrorBoundary>
  );
}

export default App;
