import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { Suspense, lazy } from 'react';
import { AuthProvider } from './contexts/AuthContext';
import { ThemeProvider } from './contexts/ThemeContext';
import { ToastProvider } from './contexts/ToastContext';
import { ErrorBoundary } from './components/common/ErrorBoundary';
import { LoadingSpinner } from './components/ui/LoadingSpinner';
import { queryClient } from './lib/queryClient';
import { useAuth } from './contexts/AuthContext';
import { Layout } from './components/layout/Layout';

// Lazy load pages for better code splitting
const Login = lazy(() => import('./pages/Login').then(module => ({ default: module.Login })));
const Dashboard = lazy(() => import('./pages/Dashboard').then(module => ({ default: module.Dashboard })));
const Users = lazy(() => import('./pages/Users').then(module => ({ default: module.Users })));
const Reports = lazy(() => import('./pages/Reports').then(module => ({ default: module.Reports })));
const Notifications = lazy(() => import('./pages/Notifications').then(module => ({ default: module.Notifications })));

// Lazy load admin pages for better code splitting
// Roles Pages
const RolesListPage = lazy(() => import('./pages/roles/roles-list/RolesListPage'));
const RoleFormPage = lazy(() => import('./pages/roles/role-form/RoleFormPage'));
const RoleDetailPage = lazy(() => import('./pages/roles/role-detail/RoleDetailPage'));
const RolePermissionsPage = lazy(() => import('./pages/roles/role-permissions/RolePermissionsPage'));

// Admin Users Pages
const AdminUsersListPage = lazy(() => import('./pages/admin-users/admin-users-list/AdminUsersListPage'));
const AdminUserFormPage = lazy(() => import('./pages/admin-users/admin-user-form/AdminUserFormPage'));
const AdminUserDetailPage = lazy(() => import('./pages/admin-users/admin-user-detail/AdminUserDetailPage'));

// Permissions Pages
const PermissionsListPage = lazy(() => import('./pages/permissions/permissions-list/PermissionsListPage'));
const PermissionFormPage = lazy(() => import('./pages/permissions/permission-form/PermissionFormPage'));

// Product Options Pages
const ProductOptionsListPage = lazy(() => import('./pages/product-options/product-options-list/ProductOptionsListPage'));
const ProductOptionFormPage = lazy(() => import('./pages/product-options/product-option-form/ProductOptionFormPage'));

// Categories Pages
const CategoriesListPage = lazy(() => import('./pages/categories/categories-list/CategoriesListPage'));
const CategoryFormPage = lazy(() => import('./pages/categories/category-form/CategoryFormPage'));

// Discount Codes Pages
const DiscountCodesListPage = lazy(() => import('./pages/discount-codes/discount-codes-list/DiscountCodesListPage'));
const DiscountCodeFormPage = lazy(() => import('./pages/discount-codes/discount-code-form/DiscountCodeFormPage'));

// Orders Pages
const OrdersListPage = lazy(() => import('./pages/orders/orders-list/OrdersListPage'));
const OrderDetailPage = lazy(() => import('./pages/orders/order-detail/OrderDetailPage'));

// Users Admin Pages
const UsersAdminListPage = lazy(() => import('./pages/users-admin/users-admin-list/UsersAdminListPage'));
const UserAdminDetailPage = lazy(() => import('./pages/users-admin/user-admin-detail/UserAdminDetailPage'));
const UserAdminFormPage = lazy(() => import('./pages/users-admin/user-admin-form/UserAdminFormPage'));

// Products Pages
const ProductsListPage = lazy(() => import('./pages/products/products-list/ProductsListPage'));
const ProductFormPage = lazy(() => import('./pages/products/product-form/ProductFormPage'));
const ProductDetailPage = lazy(() => import('./pages/products/product-detail/ProductDetailPage'));

// Landing Hero Page
const HeroSliderPage = lazy(() => import('./pages/landing-hero/HeroSliderPage'));

// Shipping Methods Pages
const ShippingMethodsListPage = lazy(() => import('./pages/shipping-methods/shipping-methods-list/ShippingMethodsListPage'));
const ShippingMethodFormPage = lazy(() => import('./pages/shipping-methods/shipping-method-form/ShippingMethodFormPage'));
const TicketsListPage = lazy(() => import('./pages/tickets/tickets-list/TicketsListPage'));
const TicketDetailPage = lazy(() => import('./pages/tickets/ticket-detail/TicketDetailPage'));
const TicketConfigPage = lazy(() => import('./pages/tickets/ticket-config/TicketConfigPage'));

// Payment IPG Page
const IPGListPage = lazy(() => import('./pages/payment-ipg/ipg-list/IPGListPage'));

// Payment Card Page
const CardFormPage = lazy(() => import('./pages/payment-card/card-form/CardFormPage'));

// Wallet Page
const WalletListPage = lazy(() => import('./pages/wallet/wallet-list/WalletListPage'));

// Reports Pages
const DiscountUsageReportPage = lazy(() => import('./pages/reports/discount-statistics/discount-usage-report/DiscountUsageReportPage'));
const CustomerDiscountUsagePage = lazy(() => import('./pages/reports/discount-statistics/customer-discount-usage/CustomerDiscountUsagePage'));
const PaymentMethodsReportPage = lazy(() => import('./pages/reports/payment-statistics/payment-methods-report/PaymentMethodsReportPage'));
const ShipmentsByMethodReportPage = lazy(() => import('./pages/reports/shipment-statistics/shipments-by-method-report/ShipmentsByMethodReportPage'));

// Product Comments Page
const ProductCommentsListPage = lazy(() => import('./pages/products/comments/comments-list/ProductCommentsListPage'));

const ProtectedRoute = ({ children }: { children: any }) => {
    const { user, isLoading } = useAuth();

    if (isLoading) {
        return (
            <Layout>
                <div className="flex items-center justify-center py-12">
                    <LoadingSpinner />
                </div>
            </Layout>
        );
    }

    return user ? children : <Navigate to="/login" replace />;
};

const AppRoutes = () => {
    return (
        <Routes>
            <Route path="/login" element={<Login />} />
            <Route path="/" element={
                <ProtectedRoute>
                    <Layout />
                </ProtectedRoute>
            }>
                <Route index element={<Dashboard />} />
                <Route path="users" element={<Users />} />
                <Route path="products" element={<ProductsListPage />} />
                <Route path="reports" element={<Reports />} />
                <Route path="notifications" element={<Notifications />} />

                {/* Roles Routes */}
                <Route path="roles" element={<RolesListPage />} />
                <Route path="roles/create" element={<RoleFormPage />} />
                <Route path="roles/:id" element={<RoleDetailPage />} />
                <Route path="roles/:id/edit" element={<RoleFormPage />} />
                <Route path="roles/:id/permissions" element={<RolePermissionsPage />} />

                {/* Admin Users Routes */}
                <Route path="admin-users" element={<AdminUsersListPage />} />
                <Route path="admin-users/create" element={<AdminUserFormPage />} />
                <Route path="admin-users/:id" element={<AdminUserDetailPage />} />
                <Route path="admin-users/:id/edit" element={<AdminUserFormPage />} />

                {/* Permissions Routes */}
                <Route path="permissions" element={<PermissionsListPage />} />
                <Route path="permissions/create" element={<PermissionFormPage />} />
                <Route path="permissions/:id/edit" element={<PermissionFormPage />} />

                {/* Product Options Routes */}
                <Route path="product-options" element={<ProductOptionsListPage />} />
                <Route path="product-options/create" element={<ProductOptionFormPage />} />
                <Route path="product-options/:id/edit" element={<ProductOptionFormPage />} />

                {/* Categories Routes */}
                <Route path="categories" element={<CategoriesListPage />} />
                <Route path="categories/create" element={<CategoryFormPage />} />
                <Route path="categories/:id/edit" element={<CategoryFormPage />} />

                {/* Discount Codes Routes */}
                <Route path="discount-codes" element={<DiscountCodesListPage />} />
                <Route path="discount-codes/create" element={<DiscountCodeFormPage />} />
                <Route path="discount-codes/:id/edit" element={<DiscountCodeFormPage />} />

                {/* Orders Routes */}
                <Route path="orders" element={<OrdersListPage />} />
                <Route path="orders/:id" element={<OrderDetailPage />} />

                {/* Users Admin Routes */}
                <Route path="users-admin" element={<UsersAdminListPage />} />
                <Route path="users-admin/create" element={<UserAdminFormPage />} />
                <Route path="users-admin/:id" element={<UserAdminDetailPage />} />
                <Route path="users-admin/:id/edit" element={<UserAdminFormPage />} />

                {/* Landing Hero Route */}
                <Route path="landing-hero" element={<HeroSliderPage />} />

                {/* Shipping Methods Routes */}
                <Route path="shipping-methods" element={<ShippingMethodsListPage />} />
                <Route path="shipping-methods/create" element={<ShippingMethodFormPage />} />
                <Route path="shipping-methods/:id/edit" element={<ShippingMethodFormPage />} />

                <Route path="tickets" element={<TicketsListPage />} />
                <Route path="tickets/config" element={<TicketConfigPage />} />
                <Route path="tickets/:id" element={<TicketDetailPage />} />

                {/* Products Routes */}
                <Route path="products/create" element={<ProductFormPage />} />
                <Route path="products/:id" element={<ProductDetailPage />} />
                <Route path="products/:id/edit" element={<ProductFormPage />} />
                <Route path="products/comments" element={<ProductCommentsListPage />} />

                {/* Payment IPG Route */}
                <Route path="payment-ipg" element={<IPGListPage />} />

                {/* Payment Card Route */}
                <Route path="payment-card" element={<CardFormPage />} />

                {/* Wallet Route */}
                <Route path="wallet" element={<WalletListPage />} />

                {/* Reports Routes */}
                <Route path="reports/discount-usage" element={<DiscountUsageReportPage />} />
                <Route path="reports/customer-discount-usage" element={<CustomerDiscountUsagePage />} />
                <Route path="reports/payment-methods" element={<PaymentMethodsReportPage />} />
                <Route path="reports/shipments-by-method" element={<ShipmentsByMethodReportPage />} />
            </Route>
        </Routes>
    );
};

const App = () => {
    return (
        <ErrorBoundary>
            <QueryClientProvider client={queryClient}>
                <ThemeProvider>
                    <ToastProvider>
                        <AuthProvider>
                            <Router>
                                <Suspense fallback={
                                    <Layout>
                                        <div className="flex items-center justify-center py-12">
                                            <LoadingSpinner />
                                        </div>
                                    </Layout>
                                }>
                                    <AppRoutes />
                                </Suspense>
                            </Router>
                        </AuthProvider>
                    </ToastProvider>
                </ThemeProvider>
                <ReactQueryDevtools initialIsOpen={false} />
            </QueryClientProvider>
        </ErrorBoundary>
    );
};

export default App; 