import { useEffect, lazy, Suspense } from 'react';
import { 
  BrowserRouter, 
  Routes, 
  Route, 
  Navigate 
} from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { GlobalLoadingProvider } from './contexts/GlobalLoadingContext';
import { CookieConsentProvider } from './contexts/CookieConsentContext';
import { CurrencyProvider } from './contexts/CurrencyContext';
import { CompanySettingsProvider } from './contexts/CompanySettingsContext';
import { AuthModalProvider } from './contexts/AuthModalContext';
import OfflineIndicator from './components/common/OfflineIndicator';
import CookieConsentBanner from './components/common/CookieConsentBanner';
import CookiePreferencesModal from './components/common/CookiePreferencesModal';
import AnalyticsLoader from './components/common/AnalyticsLoader';
import Loading from './components/common/Loading';
import ScrollToTop from './components/common/ScrollToTop';
import AuthModalManager from './components/modals/AuthModalManager';
import ResetPasswordRouteHandler from './components/ResetPasswordRouteHandler';

import useAuthStore from './store/useAuthStore';
import useFavoritesStore from './store/useFavoritesStore';

import { LayoutMain } from './components/layout';
import AdminLayout from './pages/AdminLayout';

import { 
  ProtectedRoute, 
  AdminRoute,
  StaffRoute,
  AccountantRoute,
  CustomerRoute
} from './components/auth';

const HomePage = lazy(() => import('./pages/HomePage'));
const DashboardPage = lazy(() => import('./pages/customer/DashboardPage'));
const RoomListPage = lazy(() => import('./pages/customer/RoomListPage'));
const RoomDetailPage = lazy(() => import('./pages/customer/RoomDetailPage'));
const SearchResultsPage = lazy(() => import('./pages/customer/SearchResultsPage'));
const FavoritesPage = lazy(() => import('./pages/customer/FavoritesPage'));
const MyBookingsPage = lazy(() => import('./pages/customer/MyBookingsPage'));
const BookingSuccessPage = lazy(() => import('./pages/customer/BookingSuccessPage') as Promise<{ default: React.ComponentType<any> }>);
const BookingDetailPage = lazy(() => import('./pages/customer/BookingDetailPage'));
const FullPaymentPage = lazy(() => import('./pages/customer/FullPaymentPage'));
const PaymentConfirmationPage = lazy(() => import('./pages/customer/PaymentConfirmationPage'));
const PaymentResultPage = lazy(() => import('./pages/customer/PaymentResultPage'));
const PayPalReturnPage = lazy(() => import('./pages/customer/PayPalReturnPage'));
const PayPalCancelPage = lazy(() => import('./pages/customer/PayPalCancelPage'));
const InvoicePage = lazy(() => import('./pages/customer/InvoicePage'));
const ProfilePage = lazy(() => import('./pages/customer/ProfilePage'));
const LoyaltyPage = lazy(() => import('./pages/customer/LoyaltyPage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));
const ContactPage = lazy(() => import('./pages/ContactPage'));
const PrivacyPolicyPage = lazy(() => import('./pages/PrivacyPolicyPage'));
const TermsPage = lazy(() => import('./pages/TermsPage'));
const RefundsPolicyPage = lazy(() => import('./pages/RefundsPolicyPage'));
const CancellationPolicyPage = lazy(() => import('./pages/CancellationPolicyPage'));
const AccessibilityPage = lazy(() => import('./pages/AccessibilityPage'));
const FAQPage = lazy(() => import('./pages/FAQPage'));

const AdminDashboardPage = lazy(() => import('./pages/admin/DashboardPage'));
const InvoiceManagementPage = lazy(() => import('./pages/admin/InvoiceManagementPage'));
const PaymentManagementPage = lazy(() => import('./pages/admin/PaymentManagementPage'));
const UserManagementPage = lazy(() => import('./pages/admin/UserManagementPage'));
const GuestProfilePage = lazy(() => import('./pages/admin/GuestProfilePage'));
const BookingManagementPage = lazy(() => import('./pages/admin/BookingManagementPage'));
const PageContentDashboardPage = lazy(() => import('./pages/admin/PageContentDashboard'));
const AnalyticsDashboardPage = lazy(() => import('./pages/admin/AnalyticsDashboardPage'));
const BusinessDashboardPage = lazy(() => import('./pages/admin/BusinessDashboardPage'));
const SettingsPage = lazy(() => import('./pages/admin/SettingsPage'));
const ReceptionDashboardPage = lazy(() => import('./pages/admin/ReceptionDashboardPage'));
const LoyaltyManagementPage = lazy(() => import('./pages/admin/LoyaltyManagementPage'));

const StaffDashboardPage = lazy(() => import('./pages/staff/DashboardPage'));
const ChatManagementPage = lazy(() => import('./pages/staff/ChatManagementPage'));
const StaffLayout = lazy(() => import('./pages/StaffLayout'));

const AccountantDashboardPage = lazy(() => import('./pages/accountant/DashboardPage'));
const AccountantLayout = lazy(() => import('./pages/AccountantLayout'));

const NotFoundPage = lazy(() => import('./pages/NotFoundPage'));

function App() {
  
  const { 
    isAuthenticated, 
    userInfo, 
    logout, 
    initializeAuth 
  } = useAuthStore();
  
  const { 
    fetchFavorites, 
    syncGuestFavorites,
    loadGuestFavorites,
  } = useFavoritesStore();

  
  useEffect(() => {
    initializeAuth();
  }, [initializeAuth]);

  
  useEffect(() => {
    if (isAuthenticated) {
      
      syncGuestFavorites().then(() => {
        fetchFavorites();
      });
    } else {
      
      loadGuestFavorites();
    }
  }, [
    isAuthenticated, 
    fetchFavorites, 
    syncGuestFavorites,
    loadGuestFavorites,
  ]);

  
  const handleLogout = async () => {
    await logout();
  };

  return (
    <GlobalLoadingProvider>
      <CookieConsentProvider>
        <CurrencyProvider>
          <CompanySettingsProvider>
            <AuthModalProvider>
      <BrowserRouter
        future={{
          v7_startTransition: true,
          v7_relativeSplatPath: true,
        }}
      >
        <ScrollToTop />
        <Suspense fallback={<Loading fullScreen text="Loading page..." />}>
          <Routes>
        {}
        <Route 
          path="/" 
          element={
            <LayoutMain 
              isAuthenticated={isAuthenticated}
              userInfo={userInfo}
              onLogout={handleLogout}
            />
          }
        >
          <Route index element={<HomePage />} />
          <Route 
            path="rooms" 
            element={<RoomListPage />} 
          />
          <Route 
            path="rooms/search" 
            element={<SearchResultsPage />} 
          />
          <Route 
            path="rooms/:room_number" 
            element={<RoomDetailPage />} 
          />
          <Route 
            path="favorites" 
            element={
              <CustomerRoute>
                <FavoritesPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment-result" 
            element={<PaymentResultPage />} 
          />
          <Route 
            path="payment/paypal/return" 
            element={<PayPalReturnPage />} 
          />
          <Route 
            path="payment/paypal/cancel" 
            element={<PayPalCancelPage />} 
          />
          <Route 
            path="invoices/:id" 
            element={
              <ProtectedRoute>
                <InvoicePage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="about" 
            element={<AboutPage />} 
          />
          <Route 
            path="contact" 
            element={<ContactPage />} 
          />
          <Route 
            path="privacy" 
            element={<PrivacyPolicyPage />} 
          />
          <Route 
            path="terms" 
            element={<TermsPage />} 
          />
          <Route 
            path="refunds" 
            element={<RefundsPolicyPage />} 
          />
          <Route 
            path="cancellation" 
            element={<CancellationPolicyPage />} 
          />
          <Route 
            path="accessibility" 
            element={<AccessibilityPage />} 
          />
          <Route 
            path="faq" 
            element={<FAQPage />} 
          />
          
          {}
          <Route 
            path="dashboard" 
            element={
              <ProtectedRoute>
                <DashboardPage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="booking-success/:id" 
            element={
              <CustomerRoute>
                <BookingSuccessPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="bookings" 
            element={
              <CustomerRoute>
                <MyBookingsPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="bookings/:id" 
            element={
              <CustomerRoute>
                <BookingDetailPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment/:bookingId" 
            element={
              <CustomerRoute>
                <FullPaymentPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="payment-confirmation/:id" 
            element={
              <CustomerRoute>
                <PaymentConfirmationPage />
              </CustomerRoute>
            } 
          />
          <Route 
            path="profile" 
            element={
              <ProtectedRoute>
                <ProfilePage />
              </ProtectedRoute>
            } 
          />
          <Route 
            path="loyalty" 
            element={
              <CustomerRoute>
                <LoyaltyPage />
              </CustomerRoute>
            } 
          />
        </Route>

        {}
        <Route 
          path="/reset-password/:token" 
          element={<ResetPasswordRouteHandler />} 
        />

        {}
        <Route 
          path="/admin" 
          element={
            <AdminRoute>
              <AdminLayout />
            </AdminRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<AdminDashboardPage />} />
          <Route 
            path="users" 
            element={<UserManagementPage />} 
          />
          <Route
            path="business" 
            element={<BusinessDashboardPage />} 
          />
          <Route 
            path="reception" 
            element={<ReceptionDashboardPage />} 
          />
          <Route 
            path="page-content" 
            element={<PageContentDashboardPage />} 
          />
          <Route 
            path="analytics" 
            element={<AnalyticsDashboardPage />} 
          />
          <Route
            path="settings" 
            element={<SettingsPage />} 
          />
          <Route
            path="invoices" 
            element={<InvoiceManagementPage />} 
          />
          <Route
            path="invoices/:id" 
            element={<InvoicePage />} 
          />
          <Route
            path="payments" 
            element={<PaymentManagementPage />} 
          />
          <Route
            path="loyalty" 
            element={<LoyaltyManagementPage />} 
          />
          <Route
            path="guest-profiles" 
            element={<GuestProfilePage />} 
          />
        </Route>

        {}
        <Route 
          path="/staff" 
          element={
            <StaffRoute>
              <StaffLayout />
            </StaffRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<StaffDashboardPage />} />
          <Route 
            path="bookings" 
            element={<BookingManagementPage />} 
          />
          <Route 
            path="reception" 
            element={<ReceptionDashboardPage />} 
          />
          <Route
            path="payments" 
            element={<PaymentManagementPage />} 
          />
          <Route 
            path="reports" 
            element={<AnalyticsDashboardPage />} 
          />
          <Route 
            path="chats" 
            element={<ChatManagementPage />} 
          />
          <Route
            path="loyalty" 
            element={<LoyaltyManagementPage />} 
          />
          <Route
            path="guest-profiles" 
            element={<GuestProfilePage />} 
          />
        </Route>

        {/* Accountant Routes */}
        <Route 
          path="/accountant" 
          element={
            <AccountantRoute>
              <AccountantLayout />
            </AccountantRoute>
          }
        >
          <Route 
            index 
            element={<Navigate to="dashboard" replace />} 
          />
          <Route path="dashboard" element={<AccountantDashboardPage />} />
          <Route 
            path="payments" 
            element={<PaymentManagementPage />} 
          />
          <Route 
            path="invoices" 
            element={<InvoiceManagementPage />} 
          />
          <Route 
            path="reports" 
            element={<AnalyticsDashboardPage />} 
          />
        </Route>

        {}
        <Route 
          path="*" 
          element={<NotFoundPage />} 
        />
      </Routes>
      
          <ToastContainer 
            position="top-right"
            autoClose={3000}
            hideProgressBar={false}
            newestOnTop
            closeOnClick
            rtl={false}
            pauseOnFocusLoss
            draggable
            pauseOnHover
            theme="light"
            toastClassName="rounded-lg shadow-lg"
            bodyClassName="text-sm font-medium"
          />
          <OfflineIndicator />
          <CookieConsentBanner />
          <CookiePreferencesModal />
          <AnalyticsLoader />
          <AuthModalManager />
        </Suspense>
      </BrowserRouter>
            </AuthModalProvider>
          </CompanySettingsProvider>
        </CurrencyProvider>
      </CookieConsentProvider>
    </GlobalLoadingProvider>
  );
}

export default App;
