import { lazy, Suspense, useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { AuthProvider, useAuth } from "@/contexts/AuthContext";
import { ThemeProvider } from "@/components/ThemeProvider";
import CookieConsent from "@/components/CookieConsent";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useSetupCheck } from "@/hooks/useSetupCheck";
import { useSystemSettings } from "@/hooks/useSystemSettings";
import Maintenance from "@/pages/Maintenance";
import CustomCSSInjector from "@/components/CustomCSSInjector";

// Lazy load all pages for code splitting
const Index = lazy(() => import("./pages/Index"));
const AppBuilder = lazy(() => import("./pages/AppBuilder"));
const Auth = lazy(() => import("./pages/Auth"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));
const Subscription = lazy(() => import("./pages/Subscription"));
const Privacy = lazy(() => import("./pages/Privacy"));
const Terms = lazy(() => import("./pages/Terms"));
const Install = lazy(() => import("./pages/Install"));
const Admin = lazy(() => import("./pages/Admin"));
const AdminSetup = lazy(() => import("./pages/AdminSetup"));
const StyleGuide = lazy(() => import("./pages/StyleGuide"));
const BuildHistory = lazy(() => import("./pages/BuildHistory"));
const PaymentHistory = lazy(() => import("./pages/PaymentHistory"));
const Help = lazy(() => import("./pages/Help"));
const NotFound = lazy(() => import("./pages/NotFound"));

const queryClient = new QueryClient();

const AppRoutes = () => {
  const { needsSetup, loading: setupLoading } = useSetupCheck();
  const { settings, loaded: settingsLoaded } = useSystemSettings();
  const { user } = useAuth();
  const [isAdmin, setIsAdmin] = useState(false);

  // Check admin role for maintenance bypass
  useEffect(() => {
    if (!user) { setIsAdmin(false); return; }
    supabase.rpc("get_user_role", { _user_id: user.id }).then(({ data }) => {
      setIsAdmin(data === "admin");
    });
  }, [user]);

  // Show maintenance page for non-admins when enabled
  if (settingsLoaded && settings.maintenance_mode && !isAdmin) {
    return <Maintenance />;
  }

  // Protected Route wrapper - must be inside AuthProvider
  const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
    const { user, session, loading } = useAuth();

    if (loading || setupLoading) {
      return <LoadingSpinner fullScreen />;
    }

    // If setup is needed, redirect to setup
    if (needsSetup) {
      return <Navigate to="/setup" replace />;
    }

    if (!user || !session) {
      return <Navigate to="/auth" replace />;
    }

    return <>{children}</>;
  };

  // Public route that requires setup check
  const PublicRoute = ({ children }: { children: React.ReactNode }) => {
    if (setupLoading) {
      return <LoadingSpinner fullScreen />;
    }

    // If setup is needed, redirect to setup
    if (needsSetup) {
      return <Navigate to="/setup" replace />;
    }

    return <>{children}</>;
  };

  // Setup route - only accessible when setup is needed
  const SetupRoute = ({ children }: { children: React.ReactNode }) => {
    if (setupLoading) {
      return <LoadingSpinner fullScreen />;
    }

    // If setup is complete, redirect to auth
    if (needsSetup === false) {
      return <Navigate to="/auth" replace />;
    }

    return <>{children}</>;
  };

  return (
    <Suspense fallback={<LoadingSpinner fullScreen />}>
      <Routes>
        <Route path="/" element={<PublicRoute><Index /></PublicRoute>} />
        <Route path="/auth" element={<PublicRoute><Auth /></PublicRoute>} />
        
        <Route path="/privacy" element={<Privacy />} />
        <Route path="/terms" element={<Terms />} />
        <Route path="/install" element={<Install />} />
        <Route path="/setup" element={<SetupRoute><AdminSetup /></SetupRoute>} />
        <Route
          path="/dashboard"
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          }
        />
        <Route
          path="/builder"
          element={
            <ProtectedRoute>
              <AppBuilder />
            </ProtectedRoute>
          }
        />
        <Route
          path="/settings"
          element={
            <ProtectedRoute>
              <Settings />
            </ProtectedRoute>
          }
        />
        <Route
          path="/subscription"
          element={
            <ProtectedRoute>
              <Subscription />
            </ProtectedRoute>
          }
        />
        <Route
          path="/admin"
          element={
            <ProtectedRoute>
              <Admin />
            </ProtectedRoute>
          }
        />
        <Route path="/style-guide" element={<StyleGuide />} />
        <Route
          path="/build-history"
          element={
            <ProtectedRoute>
              <BuildHistory />
            </ProtectedRoute>
          }
        />
        <Route
          path="/payment-history"
          element={
            <ProtectedRoute>
              <PaymentHistory />
            </ProtectedRoute>
          }
        />
        <Route path="/help" element={<Help />} />
        {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Suspense>
  );
};

const App = () => (
  <ThemeProvider>
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <CustomCSSInjector />
        <Toaster />
        <Sonner />
        <BrowserRouter>
          <AuthProvider>
            <AppRoutes />
            <CookieConsent />
          </AuthProvider>
        </BrowserRouter>
      </TooltipProvider>
    </QueryClientProvider>
  </ThemeProvider>
);

export default App;
