import React, { lazy, ReactNode } from 'react';
import { Navigate, RouteObject, useRoutes } from 'react-router-dom';
import { AdminRoute, StaffRoute, AccountantRoute, CustomerRoute, HousekeepingRoute } from '../features/auth/components';
import ErrorBoundaryRoute from '../shared/components/ErrorBoundaryRoute';
import LayoutMain from '../shared/components/LayoutMain';
import AdminLayout from '../pages/AdminLayout';
import StaffLayout from '../pages/StaffLayout';
import AccountantLayout from '../pages/AccountantLayout';
import HousekeepingLayout from '../pages/HousekeepingLayout';

// Public pages
const HomePage = lazy(() => import('../features/content/pages/HomePage'));
const RoomListPage = lazy(() => import('../pages/customer/RoomListPage'));
const RoomDetailPage = lazy(() => import('../pages/customer/RoomDetailPage'));
const SearchResultsPage = lazy(() => import('../pages/customer/SearchResultsPage'));
const AboutPage = lazy(() => import('../features/content/pages/AboutPage'));
const ContactPage = lazy(() => import('../features/content/pages/ContactPage'));
const PrivacyPolicyPage = lazy(() => import('../features/content/pages/PrivacyPolicyPage'));
const TermsPage = lazy(() => import('../features/content/pages/TermsPage'));
const RefundsPolicyPage = lazy(() => import('../features/content/pages/RefundsPolicyPage'));
const CancellationPolicyPage = lazy(() => import('../features/content/pages/CancellationPolicyPage'));
const AccessibilityPage = lazy(() => import('../features/content/pages/AccessibilityPage'));
const FAQPage = lazy(() => import('../features/content/pages/FAQPage'));
const BlogPage = lazy(() => import('../features/content/pages/BlogPage'));
const BlogDetailPage = lazy(() => import('../features/content/pages/BlogDetailPage'));
const ServicesPage = lazy(() => import('../features/content/pages/ServicesPage'));
const ServiceDetailPage = lazy(() => import('../features/content/pages/ServiceDetailPage'));

// Customer pages
const DashboardPage = lazy(() => import('../pages/customer/DashboardPage'));
const FavoritesPage = lazy(() => import('../pages/customer/FavoritesPage'));
const MyBookingsPage = lazy(() => import('../pages/customer/MyBookingsPage'));
const BookingSuccessPage = lazy(() => import('../pages/customer/BookingSuccessPage'));
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 BoricaReturnPage = lazy(() => import('../pages/customer/BoricaReturnPage'));
const InvoicePage = lazy(() => import('../pages/customer/InvoicePage'));
const ProfilePage = lazy(() => import('../pages/customer/ProfilePage'));
const LoyaltyPage = lazy(() => import('../pages/customer/LoyaltyPage'));
const GroupBookingPage = lazy(() => import('../pages/customer/GroupBookingPage'));
const ComplaintPage = lazy(() => import('../pages/customer/ComplaintPage'));
const GuestRequestsPage = lazy(() => import('../pages/customer/GuestRequestsPage'));
const GDPRPage = lazy(() => import('../pages/customer/GDPRPage'));
const GDPRDeletionConfirmPage = lazy(() => import('../pages/customer/GDPRDeletionConfirmPage'));
const SessionManagementPage = lazy(() => import('../pages/customer/SessionManagementPage'));

// Admin pages
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 GroupBookingManagementPage = lazy(() => import('../pages/admin/GroupBookingManagementPage'));
const AdminBookingManagementPage = lazy(() => import('../pages/admin/BookingManagementPage'));
const PageContentDashboardPage = lazy(() => import('../pages/admin/PageContentDashboard'));
const AnalyticsDashboardPage = lazy(() => import('../pages/admin/AnalyticsDashboardPage'));
const PromotionsManagementPage = lazy(() => import('../pages/admin/PromotionsManagementPage'));
const SettingsPage = lazy(() => import('../pages/admin/SettingsPage'));
const TaskManagementPage = lazy(() => import('../pages/admin/TaskManagementPage'));
const WorkflowManagementPage = lazy(() => import('../pages/admin/WorkflowManagementPage'));
const NotificationManagementPage = lazy(() => import('../pages/admin/NotificationManagementPage'));
const ReceptionDashboardPage = lazy(() => import('../pages/admin/ReceptionDashboardPage'));
const LoyaltyManagementPage = lazy(() => import('../pages/admin/LoyaltyManagementPage'));
const AdvancedRoomManagementPage = lazy(() => import('../pages/admin/AdvancedRoomManagementPage'));
const EditRoomPage = lazy(() => import('../pages/admin/EditRoomPage'));
const RatePlanManagementPage = lazy(() => import('../pages/admin/RatePlanManagementPage'));
const PackageManagementPage = lazy(() => import('../pages/admin/PackageManagementPage'));
const SecurityManagementPage = lazy(() => import('../pages/admin/SecurityManagementPage'));
const EmailCampaignManagementPage = lazy(() => import('../pages/admin/EmailCampaignManagementPage'));
const ReviewManagementPage = lazy(() => import('../pages/admin/ReviewManagementPage'));
const BlogManagementPage = lazy(() => import('../pages/admin/BlogManagementPage'));
const ComplaintManagementPage = lazy(() => import('../pages/admin/ComplaintManagementPage'));
const FinancialAuditTrailPage = lazy(() => import('../pages/admin/FinancialAuditTrailPage'));
const ComplianceReportingPage = lazy(() => import('../pages/admin/ComplianceReportingPage'));
const ApprovalManagementPage = lazy(() => import('../pages/admin/ApprovalManagementPage'));
const GDPRManagementPage = lazy(() => import('../pages/admin/GDPRManagementPage'));
const WebhookManagementPage = lazy(() => import('../pages/admin/WebhookManagementPage'));
const APIKeyManagementPage = lazy(() => import('../pages/admin/APIKeyManagementPage'));
const BackupManagementPage = lazy(() => import('../pages/admin/BackupManagementPage'));
const ServiceManagementPage = lazy(() => import('../pages/admin/ServiceManagementPage'));
const InventoryManagementPage = lazy(() => import('../pages/admin/InventoryManagementPage'));
const MaintenanceManagementPage = lazy(() => import('../pages/admin/MaintenanceManagementPage'));
const InspectionManagementPage = lazy(() => import('../pages/admin/InspectionManagementPage'));
const StaffShiftDashboardPage = lazy(() => import('../pages/admin/StaffShiftDashboardPage'));
const AdminTeamChatPage = lazy(() => import('../pages/admin/TeamChatPage'));
const AdminProfilePage = lazy(() => import('../pages/admin/ProfilePage'));
const InvoiceEditPage = lazy(() => import('../pages/admin/InvoiceEditPage'));

// Staff pages
const StaffDashboardPage = lazy(() => import('../pages/staff/DashboardPage'));
const StaffInventoryViewPage = lazy(() => import('../pages/staff/InventoryViewPage'));
const StaffShiftViewPage = lazy(() => import('../pages/staff/ShiftViewPage'));
const StaffTeamChatPage = lazy(() => import('../pages/staff/TeamChatPage'));
const StaffBookingManagementPage = lazy(() => import('../pages/staff/BookingManagementPage'));
const StaffReceptionDashboardPage = lazy(() => import('../pages/staff/ReceptionDashboardPage'));
const StaffPaymentManagementPage = lazy(() => import('../pages/staff/PaymentManagementPage'));
const StaffAnalyticsDashboardPage = lazy(() => import('../pages/staff/AnalyticsDashboardPage'));
const StaffGuestProfilePage = lazy(() => import('../pages/staff/GuestProfilePage'));
const StaffAdvancedRoomManagementPage = lazy(() => import('../pages/staff/AdvancedRoomManagementPage'));
const ChatManagementPage = lazy(() => import('../pages/staff/ChatManagementPage'));
const GuestRequestManagementPage = lazy(() => import('../pages/staff/GuestRequestManagementPage'));
const GuestCommunicationPage = lazy(() => import('../pages/staff/GuestCommunicationPage'));
const IncidentComplaintManagementPage = lazy(() => import('../pages/staff/IncidentComplaintManagementPage'));
const UpsellManagementPage = lazy(() => import('../pages/staff/UpsellManagementPage'));
const StaffLoyaltyManagementPage = lazy(() => import('../pages/staff/LoyaltyManagementPage'));
const StaffProfilePage = lazy(() => import('../pages/staff/ProfilePage'));

// Accountant pages
const AccountantDashboardPage = lazy(() => import('../pages/accountant/DashboardPage'));
const AccountantPaymentManagementPage = lazy(() => import('../pages/accountant/PaymentManagementPage'));
const AccountantInvoiceManagementPage = lazy(() => import('../pages/accountant/InvoiceManagementPage'));
const GLManagementPage = lazy(() => import('../pages/accountant/GLManagementPage'));
const AccountantApprovalManagementPage = lazy(() => import('../pages/accountant/ApprovalManagementPage'));
const FinancialReportsPage = lazy(() => import('../pages/accountant/FinancialReportsPage'));
const ReconciliationPage = lazy(() => import('../pages/accountant/ReconciliationPage'));
const AuditTrailPage = lazy(() => import('../pages/accountant/AuditTrailPage'));
const AccountantSecurityManagementPage = lazy(() => import('../pages/accountant/SecurityManagementPage'));
const AccountantProfilePage = lazy(() => import('../pages/accountant/ProfilePage'));

// Housekeeping pages
const HousekeepingDashboardPage = lazy(() => import('../pages/housekeeping/DashboardPage'));
const HousekeepingTasksPage = lazy(() => import('../pages/housekeeping/TasksPage'));
const HousekeepingShiftViewPage = lazy(() => import('../pages/housekeeping/ShiftViewPage'));
const HousekeepingProfilePage = lazy(() => import('../pages/housekeeping/ProfilePage'));
const HousekeepingTeamChatPage = lazy(() => import('../pages/housekeeping/TeamChatPage'));

// Auth pages
const StaffLoginPage = lazy(() => import('../features/auth/pages/StaffLoginPage'));
const AdminLoginPage = lazy(() => import('../features/auth/pages/AdminLoginPage'));
const HousekeepingLoginPage = lazy(() => import('../features/auth/pages/HousekeepingLoginPage'));
const AccountantLoginPage = lazy(() => import('../features/auth/pages/AccountantLoginPage'));
const ResetPasswordRouteHandler = lazy(() => import('../features/auth/components/ResetPasswordRouteHandler'));

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

type AuthUser = {
  id: number;
  name: string;
  email: string;
  role: string;
  avatar?: string;
};

type AuthProps = {
  isAuthenticated: boolean;
  userInfo: AuthUser | null;
  onLogout: () => Promise<void>;
};

const withBoundary = (node: ReactNode) => (
  <ErrorBoundaryRoute>
    {node}
  </ErrorBoundaryRoute>
);

const withCustomer = (node: ReactNode) => withBoundary(
  <CustomerRoute>
    {node}
  </CustomerRoute>,
);

const buildRoutes = ({ isAuthenticated, userInfo, onLogout }: AuthProps): RouteObject[] => {
  const rootChildren: RouteObject[] = [
    { index: true, element: <HomePage /> },
    { path: 'rooms', element: <RoomListPage /> },
    { path: 'rooms/search', element: <SearchResultsPage /> },
    { path: 'rooms/:room_number', element: <RoomDetailPage /> },
    { path: 'payment-result', element: withBoundary(<PaymentResultPage />) },
    { path: 'payment/paypal/return', element: withBoundary(<PayPalReturnPage />) },
    { path: 'payment/paypal/cancel', element: withBoundary(<PayPalCancelPage />) },
    { path: 'payment/borica/return', element: withBoundary(<BoricaReturnPage />) },
    { path: 'invoices/:id', element: withCustomer(<InvoicePage />) },
    { path: 'about', element: <AboutPage /> },
    { path: 'contact', element: <ContactPage /> },
    { path: 'privacy', element: <PrivacyPolicyPage /> },
    { path: 'terms', element: <TermsPage /> },
    { path: 'refunds', element: <RefundsPolicyPage /> },
    { path: 'cancellation', element: <CancellationPolicyPage /> },
    { path: 'accessibility', element: <AccessibilityPage /> },
    { path: 'faq', element: <FAQPage /> },
    { path: 'blog', element: <BlogPage /> },
    { path: 'blog/:slug', element: <BlogDetailPage /> },
    { path: 'services', element: <ServicesPage /> },
    { path: 'services/:slug', element: <ServiceDetailPage /> },
    { path: 'favorites', element: withCustomer(<FavoritesPage />) },
    { path: 'dashboard', element: withCustomer(<DashboardPage />) },
    { path: 'booking-success/:id', element: withCustomer(<BookingSuccessPage />) },
    { path: 'bookings', element: withCustomer(<MyBookingsPage />) },
    { path: 'bookings/:id', element: withCustomer(<BookingDetailPage />) },
    { path: 'payment/:bookingId', element: withCustomer(<FullPaymentPage />) },
    { path: 'payment-confirmation/:id', element: withCustomer(<PaymentConfirmationPage />) },
    { path: 'profile', element: withCustomer(<ProfilePage />) },
    { path: 'loyalty', element: withCustomer(<LoyaltyPage />) },
    { path: 'group-bookings', element: withCustomer(<GroupBookingPage />) },
    { path: 'complaints', element: withCustomer(<ComplaintPage />) },
    { path: 'requests', element: withCustomer(<GuestRequestsPage />) },
    { path: 'guest-requests', element: withCustomer(<GuestRequestsPage />) },
    { path: 'gdpr', element: withCustomer(<GDPRPage />) },
    { path: 'gdpr/delete/confirm', element: withBoundary(<GDPRDeletionConfirmPage />) },
    { path: 'sessions', element: withCustomer(<SessionManagementPage />) },
  ];

  const adminChildren: RouteObject[] = [
    { index: true, element: <Navigate to="dashboard" replace /> },
    { path: 'dashboard', element: <AdminDashboardPage /> },
    { path: 'users', element: <UserManagementPage /> },
    { path: 'promotions', element: <PromotionsManagementPage /> },
    { path: 'reception', element: <ReceptionDashboardPage /> },
    { path: 'advanced-rooms', element: <AdvancedRoomManagementPage /> },
    { path: 'rooms/:id/edit', element: <EditRoomPage /> },
    { path: 'page-content', element: <PageContentDashboardPage /> },
    { path: 'analytics', element: <AnalyticsDashboardPage /> },
    { path: 'tasks', element: <TaskManagementPage /> },
    { path: 'workflows', element: <WorkflowManagementPage /> },
    { path: 'notifications', element: <NotificationManagementPage /> },
    { path: 'settings', element: <SettingsPage /> },
    { path: 'invoices', element: <InvoiceManagementPage /> },
    { path: 'invoices/:id/edit', element: <InvoiceEditPage /> },
    { path: 'invoices/:id', element: <InvoicePage /> },
    { path: 'payments', element: <PaymentManagementPage /> },
    { path: 'loyalty', element: <LoyaltyManagementPage /> },
    { path: 'guest-profiles', element: <GuestProfilePage /> },
    { path: 'group-bookings', element: <GroupBookingManagementPage /> },
    { path: 'bookings', element: <AdminBookingManagementPage /> },
    { path: 'rate-plans', element: <RatePlanManagementPage /> },
    { path: 'packages', element: <PackageManagementPage /> },
    { path: 'security', element: <SecurityManagementPage /> },
    { path: 'email-campaigns', element: <EmailCampaignManagementPage /> },
    { path: 'team-chat', element: <AdminTeamChatPage /> },
    { path: 'reviews', element: <ReviewManagementPage /> },
    { path: 'blog', element: <BlogManagementPage /> },
    { path: 'complaints', element: <ComplaintManagementPage /> },
    { path: 'financial-audit', element: <FinancialAuditTrailPage /> },
    { path: 'compliance', element: <ComplianceReportingPage /> },
    { path: 'approvals', element: <ApprovalManagementPage /> },
    { path: 'gdpr', element: <GDPRManagementPage /> },
    { path: 'webhooks', element: <WebhookManagementPage /> },
    { path: 'api-keys', element: <APIKeyManagementPage /> },
    { path: 'backups', element: <BackupManagementPage /> },
    { path: 'services', element: <ServiceManagementPage /> },
    { path: 'inventory', element: <InventoryManagementPage /> },
    { path: 'maintenance', element: <MaintenanceManagementPage /> },
    { path: 'inspections', element: <InspectionManagementPage /> },
    { path: 'shifts', element: <StaffShiftDashboardPage /> },
    { path: 'profile', element: <AdminProfilePage /> },
    { path: 'sessions', element: <SessionManagementPage /> },
  ].map((route) => ({
    ...route,
    element: withBoundary(route.element),
  }));

  const staffChildren: RouteObject[] = [
    { index: true, element: <Navigate to="dashboard" replace /> },
    { path: 'dashboard', element: <StaffDashboardPage /> },
    { path: 'bookings', element: <StaffBookingManagementPage /> },
    { path: 'reception', element: <StaffReceptionDashboardPage /> },
    { path: 'payments', element: <StaffPaymentManagementPage /> },
    { path: 'reports', element: <StaffAnalyticsDashboardPage /> },
    { path: 'chats', element: <ChatManagementPage /> },
    { path: 'guest-profiles', element: <StaffGuestProfilePage /> },
    { path: 'advanced-rooms', element: <StaffAdvancedRoomManagementPage /> },
    { path: 'guest-requests', element: <GuestRequestManagementPage /> },
    { path: 'guest-communication', element: <GuestCommunicationPage /> },
    { path: 'incidents-complaints', element: <IncidentComplaintManagementPage /> },
    { path: 'upsells', element: <UpsellManagementPage /> },
    { path: 'invoices/:id', element: <InvoicePage /> },
    { path: 'profile', element: <StaffProfilePage /> },
    { path: 'sessions', element: <SessionManagementPage /> },
    { path: 'inventory', element: <StaffInventoryViewPage /> },
    { path: 'loyalty', element: <StaffLoyaltyManagementPage /> },
    { path: 'shifts', element: <StaffShiftViewPage /> },
    { path: 'team-chat', element: <StaffTeamChatPage /> },
  ].map((route) => ({
    ...route,
    element: withBoundary(route.element),
  }));

  const accountantChildren: RouteObject[] = [
    { index: true, element: <Navigate to="dashboard" replace /> },
    { path: 'dashboard', element: <AccountantDashboardPage /> },
    { path: 'payments', element: <AccountantPaymentManagementPage /> },
    { path: 'invoices', element: <AccountantInvoiceManagementPage /> },
    { path: 'gl', element: <GLManagementPage /> },
    { path: 'approvals', element: <AccountantApprovalManagementPage /> },
    { path: 'reports', element: <FinancialReportsPage /> },
    { path: 'reconciliation', element: <ReconciliationPage /> },
    { path: 'audit-trail', element: <AuditTrailPage /> },
    { path: 'security', element: <AccountantSecurityManagementPage /> },
    { path: 'profile', element: <AccountantProfilePage /> },
    { path: 'sessions', element: <SessionManagementPage /> },
    { path: 'invoices/:id/edit', element: <InvoiceEditPage /> },
    { path: 'invoices/:id', element: <InvoicePage /> },
  ].map((route) => ({
    ...route,
    element: withBoundary(route.element),
  }));

  const housekeepingChildren: RouteObject[] = [
    { index: true, element: <Navigate to="dashboard" replace /> },
    { path: 'dashboard', element: <HousekeepingDashboardPage /> },
    { path: 'tasks', element: <HousekeepingTasksPage /> },
    { path: 'shifts', element: <HousekeepingShiftViewPage /> },
    { path: 'profile', element: <HousekeepingProfilePage /> },
    { path: 'sessions', element: <SessionManagementPage /> },
    { path: 'team-chat', element: <HousekeepingTeamChatPage /> },
  ].map((route) => ({
    ...route,
    element: withBoundary(route.element),
  }));

  return [
    {
      path: '/',
      element: (
        <LayoutMain 
          isAuthenticated={isAuthenticated}
          userInfo={userInfo}
          onLogout={onLogout}
        />
      ),
      children: rootChildren,
    },
    {
      path: '/staff/login',
      element: withBoundary(<StaffLoginPage />),
    },
    {
      path: '/admin/login',
      element: withBoundary(<AdminLoginPage />),
    },
    {
      path: '/housekeeping/login',
      element: withBoundary(<HousekeepingLoginPage />),
    },
    {
      path: '/accountant/login',
      element: withBoundary(<AccountantLoginPage />),
    },
    {
      path: '/reset-password/:token',
      element: withBoundary(<ResetPasswordRouteHandler />),
    },
    {
      path: '/admin',
      element: (
        <ErrorBoundaryRoute>
          <AdminRoute>
            <AdminLayout />
          </AdminRoute>
        </ErrorBoundaryRoute>
      ),
      children: adminChildren,
    },
    {
      path: '/staff',
      element: (
        <ErrorBoundaryRoute>
          <StaffRoute>
            <StaffLayout />
          </StaffRoute>
        </ErrorBoundaryRoute>
      ),
      children: staffChildren,
    },
    {
      path: '/accountant',
      element: (
        <ErrorBoundaryRoute>
          <AccountantRoute>
            <AccountantLayout />
          </AccountantRoute>
        </ErrorBoundaryRoute>
      ),
      children: accountantChildren,
    },
    {
      path: '/housekeeping',
      element: (
        <ErrorBoundaryRoute>
          <HousekeepingRoute>
            <HousekeepingLayout />
          </HousekeepingRoute>
        </ErrorBoundaryRoute>
      ),
      children: housekeepingChildren,
    },
    { path: '*', element: <NotFoundPage /> },
  ];
};

const AppRouter: React.FC<AuthProps> = (props) => {
  const routes = buildRoutes(props);
  return useRoutes(routes);
};

export default AppRouter;

