import React from "react";
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 { useAuth, AuthProvider } from "@/contexts/AuthContext";
import { CartProvider } from "@/contexts/CartContext";
import { LanguageProvider } from "@/contexts/LanguageContext";
import { CurrencyProvider } from "@/contexts/CurrencyContext";
import ErrorBoundary from "@/components/ErrorBoundary";
import FrontendLayout from "@/components/layouts/FrontendLayout";
import Index from "./pages/Index";
import SignIn from "./pages/SignIn";
import SignUp from "./pages/SignUp";
import Explore from "./pages/Explore";
import { ListingDetails } from "./pages/ListingDetails";
import OfferDetails from "./pages/OfferDetails";
import Checkout from "./pages/Checkout";
import PaymentError from "./pages/PaymentError";
import OrderConfirmation from "./pages/OrderConfirmation";
import DashboardLayout from "./components/DashboardLayout";
import Dashboard from "./pages/dashboard/Dashboard";
import AdminDashboard from "./pages/dashboard/AdminDashboard";
import ChannelManager from "./pages/dashboard/ChannelManager";
import Wallet from "./pages/dashboard/Wallet";
import MyListings from "./pages/dashboard/MyListings";
import Messages from "./pages/dashboard/Messages";
import Reviews from "./pages/dashboard/Reviews";
import Bookings from "./pages/dashboard/Bookings";
import Bookmarks from "./pages/dashboard/Bookmarks";
import Profile from "./pages/dashboard/Profile";
import Settings from "./pages/dashboard/Settings";
import Invoices from "./pages/dashboard/Invoices";
import InvoiceDetail from "./pages/dashboard/InvoiceDetail";
import HotelManagement from "./pages/dashboard/HotelManagement";
import RestaurantPOS from "./pages/dashboard/RestaurantPOS";
import VehicleManagement from "./pages/dashboard/VehicleManagement";
import Sustainability from "./pages/dashboard/Sustainability";
import Establishments from "./pages/dashboard/Establishments";
import Analytics from "./pages/dashboard/Analytics";
import SearchPlaces from "./pages/dashboard/SearchPlaces";
import SearchEstablishments from "./pages/dashboard/SearchEstablishments";
// Config pages
import APIs from "./pages/dashboard/config/APIs";
import Payments from "./pages/dashboard/config/Payments";
import Parameters from "./pages/dashboard/config/Parameters";
import Integrations from "./pages/dashboard/config/Integrations";
import Audit from "./pages/dashboard/config/Audit";
import SecurityCenter from "./pages/dashboard/config/SecurityCenter";
import PersonalizationPage from "./pages/dashboard/config/PersonalizationPage";
// POLITUR pages
import EmergencyDashboard from "./pages/dashboard/politur/EmergencyDashboard";
import PolReports from "./pages/dashboard/politur/Reports";
// Commerce pages (for retail stores)
import CommerceStore from "./pages/dashboard/commerce/Store";
import CommercePOS from "./pages/dashboard/commerce/POSTerminal";
import CommerceCustomers from "./pages/dashboard/commerce/Customers";
import CommerceInventory from "./pages/dashboard/commerce/Inventory";
import CommerceStaff from "./pages/dashboard/commerce/Staff";
import CommerceCashier from "./pages/dashboard/commerce/Cashier";
import CommerceReports from "./pages/dashboard/commerce/Reports";
// Hotel pages
import HotelRooms from "./pages/dashboard/hotel/Rooms";
import HotelCheckIn from "./pages/dashboard/hotel/CheckIn";
import HotelRoomService from "./pages/dashboard/hotel/RoomServicePage";
import HotelKeyless from "./pages/dashboard/hotel/KeylessAccess";
import HotelStaff from "./pages/dashboard/hotel/Staff";
// Restaurant pages
import RestaurantPOS_Terminal from "./pages/dashboard/restaurant/POSPage";
import RestaurantOrders from "./pages/dashboard/restaurant/Orders";
import RestaurantKitchen from "./pages/dashboard/restaurant/Kitchen";
import RestaurantBills from "./pages/dashboard/restaurant/Bills";
import RestaurantTables from "./pages/dashboard/restaurant/Tables";
import RestaurantMenu from "./pages/dashboard/restaurant/Menu";
import RestaurantInventory from "./pages/dashboard/restaurant/Inventory";
import RestaurantStaff from "./pages/dashboard/restaurant/Staff";
import NotFound from "./pages/NotFound";

const queryClient = new QueryClient();

// Protected Route Component
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated, isLoading } = useAuth();
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-lg">Loading...</div>
      </div>
    );
  }
  
  return isAuthenticated ? <>{children}</> : <Navigate to="/sign-in" />;
};

// Router component that has access to Auth context
const DashboardGate = () => {
  const { user, isLoading } = useAuth();
  
  console.log('🚪 DashboardGate - user:', user ? { email: user.email, role: (user as any)?.role, roleId: (user as any)?.roleId } : 'null');
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-lg">Loading...</div>
      </div>
    );
  }
  
  const role = (user as any)?.role;
  console.log('🚪 DashboardGate - checking role:', role, 'isAdmin?', (role === 'admin' || role === 'super_admin'));
  
  if (role === 'admin' || role === 'super_admin') {
    console.log('🚪 Redirecting to admin dashboard');
    return <Navigate to="/dashboard/admin" replace />;
  }
  
  console.log('🚪 Showing regular dashboard');
  return (
    <DashboardLayout>
      <Dashboard />
    </DashboardLayout>
  );
};

const AppRouter = () => (
  <BrowserRouter>
    <Routes>
      {/* Public Routes with Frontend Layout */}
      <Route path="/" element={
        <FrontendLayout>
          <Index />
        </FrontendLayout>
      } />
      <Route path="/sign-in" element={
        <FrontendLayout>
          <SignIn />
        </FrontendLayout>
      } />
      <Route path="/sign-up" element={
        <FrontendLayout>
          <SignUp />
        </FrontendLayout>
      } />
          <Route path="/explore" element={
            <FrontendLayout>
              <Explore />
            </FrontendLayout>
          } />
          <Route path="/explore/:category" element={
            <FrontendLayout>
              <Explore />
            </FrontendLayout>
          } />
          <Route path="/listing-details" element={
            <FrontendLayout>
              <ListingDetails />
            </FrontendLayout>
          } />
          <Route path="/offer/:slug" element={
            <FrontendLayout>
              <OfferDetails />
            </FrontendLayout>
          } />
          <Route path="/checkout" element={
            <FrontendLayout>
              <Checkout />
            </FrontendLayout>
          } />
          <Route path="/payment-error" element={
            <FrontendLayout>
              <PaymentError />
            </FrontendLayout>
          } />
          <Route path="/order-confirmation" element={
            <FrontendLayout>
              <OrderConfirmation />
            </FrontendLayout>
          } />
      
      {/* Protected Dashboard Routes */}
      <Route path="/dashboard" element={
        <ProtectedRoute>
          <DashboardGate />
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/admin" element={
        <ProtectedRoute>
          <DashboardLayout>
            <AdminDashboard />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/channel-manager" element={
        <ProtectedRoute>
          <DashboardLayout>
            <ChannelManager />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/wallet" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Wallet />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/my-listings" element={
        <ProtectedRoute>
          <DashboardLayout>
            <MyListings />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/messages" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Messages />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/reviews" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Reviews />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/bookings" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Bookings />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/bookmarks" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Bookmarks />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/profile" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Profile />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/settings" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Settings />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/invoices" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Invoices />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/invoice/:id" element={
        <ProtectedRoute>
          <DashboardLayout>
            <InvoiceDetail />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/vehicle-management" element={
        <ProtectedRoute>
          <DashboardLayout>
            <VehicleManagement />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/sustainability" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Sustainability />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/establishments" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Establishments />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/analytics" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Analytics />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/search-places" element={
        <ProtectedRoute>
          <DashboardLayout>
            <SearchPlaces />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/search-establishments" element={
        <ProtectedRoute>
          <DashboardLayout>
            <SearchEstablishments />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      {/* Commerce Routes */}
      <Route path="/dashboard/commerce/store" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceStore />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/pos" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommercePOS />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/customers" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceCustomers />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/cashier" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceCashier />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/inventory" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceInventory />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/staff" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceStaff />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/reports" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceReports />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/commerce/sales" element={
        <ProtectedRoute>
          <DashboardLayout>
            <CommerceReports />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      
          <Route path="/dashboard/hotel-management" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelManagement />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelManagement />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel/rooms" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelRooms />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel/checkin" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelCheckIn />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel/room-service" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelRoomService />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel/keyless" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelKeyless />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/hotel/staff" element={
            <ProtectedRoute>
              <DashboardLayout>
                <HotelStaff />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant-pos" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantPOS />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantPOS />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/pos" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantPOS_Terminal />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/orders" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantOrders />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/kitchen" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantKitchen />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/bills" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantBills />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/tables" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantTables />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/menu" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantMenu />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/inventory" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantInventory />
              </DashboardLayout>
            </ProtectedRoute>
          } />
          <Route path="/dashboard/restaurant/staff" element={
            <ProtectedRoute>
              <DashboardLayout>
                <RestaurantStaff />
              </DashboardLayout>
            </ProtectedRoute>
          } />
      
      {/* Config Routes */}
      <Route path="/dashboard/config/apis" element={
        <ProtectedRoute>
          <DashboardLayout>
            <APIs />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/payments" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Payments />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/parameters" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Parameters />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/integrations" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Integrations />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/audit" element={
        <ProtectedRoute>
          <DashboardLayout>
            <Audit />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/security" element={
        <ProtectedRoute>
          <DashboardLayout>
            <SecurityCenter />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/config/personalization" element={
        <ProtectedRoute>
          <DashboardLayout>
            <PersonalizationPage />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      {/* POLITUR Routes */}
      <Route path="/dashboard/politur/emergency" element={
        <ProtectedRoute>
          <DashboardLayout>
            <EmergencyDashboard />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      <Route path="/dashboard/politur/reports" element={
        <ProtectedRoute>
          <DashboardLayout>
            <PolReports />
          </DashboardLayout>
        </ProtectedRoute>
      } />
      
      {/* Catch-all route */}
      <Route path="*" element={<NotFound />} />
    </Routes>
  </BrowserRouter>
);

const App = () => (
  <QueryClientProvider client={queryClient}>
    <TooltipProvider>
      <Toaster />
      <Sonner />
      <AuthProvider>
        <LanguageProvider>
          <CurrencyProvider>
            <CartProvider>
              <ErrorBoundary>
                <AppRouter />
              </ErrorBoundary>
            </CartProvider>
          </CurrencyProvider>
        </LanguageProvider>
      </AuthProvider>
    </TooltipProvider>
  </QueryClientProvider>
);

export default App;
