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 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 Personalization from "./pages/dashboard/Personalization";
// 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/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>
          } />
          <Route path="/dashboard/personalization" element={
            <ProtectedRoute>
              <DashboardLayout>
                <Personalization />
              </DashboardLayout>
            </ProtectedRoute>
          } />
      
      {/* Catch-all route */}
      <Route path="*" element={<NotFound />} />
    </Routes>
  </BrowserRouter>
);

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

export default App;
