import { createBrowserRouter } from 'react-router-dom'
import * as Sentry from '@sentry/react'
import { lazy, Suspense } from 'react'
import { AppLayout, ProtectedRoute } from '@/components/layout'
import { RouteError } from '@/components/common/RouteError'
import { ErrorBoundary } from '@/components/common/ErrorBoundary'
import { PageLoader } from '@/components/common/PageLoader'

const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV7(createBrowserRouter)
import {
  LoginPage,
  RegisterPage,
} from '@/pages'

// Public pages
const LandingPage = lazy(() => import('@/pages/LandingPage'))
const SharedSessionPage = lazy(() => import('@/pages/SharedSessionPage'))
const SurveyPage = lazy(() => import('@/pages/SurveyPage'))
const SurveyThankYouPage = lazy(() => import('@/pages/SurveyThankYouPage'))

// Standalone auth pages
const VerifyEmailPage = lazy(() => import('@/pages/VerifyEmailPage'))
const ChangePasswordPage = lazy(() => import('@/pages/ChangePasswordPage'))
const ForgotPasswordPage = lazy(() => import('@/pages/ForgotPasswordPage'))
const ResetPasswordPage = lazy(() => import('@/pages/ResetPasswordPage'))

// Lazy load heavy pages for code splitting
const QuickStartPage = lazy(() => import('@/pages/QuickStartPage'))
const TreeLibraryPage = lazy(() => import('@/pages/TreeLibraryPage'))
const MyTreesPage = lazy(() => import('@/pages/MyTreesPage'))
const TreeNavigationPage = lazy(() => import('@/pages/TreeNavigationPage'))
const TreeEditorPage = lazy(() => import('@/pages/TreeEditorPage'))
const ProceduralEditorPage = lazy(() => import('@/pages/ProceduralEditorPage'))
const ProceduralNavigationPage = lazy(() => import('@/pages/ProceduralNavigationPage'))
const MaintenanceFlowDetailPage = lazy(() => import('@/pages/MaintenanceFlowDetailPage'))
const BatchStatusPage = lazy(() => import('@/pages/BatchStatusPage'))
const SessionHistoryPage = lazy(() => import('@/pages/SessionHistoryPage'))
const SessionDetailPage = lazy(() => import('@/pages/SessionDetailPage'))
const MySharesPage = lazy(() => import('@/pages/MySharesPage'))
const TeamAnalyticsPage = lazy(() => import('@/pages/TeamAnalyticsPage'))
const MyAnalyticsPage = lazy(() => import('@/pages/MyAnalyticsPage'))
const FeedbackPage = lazy(() => import('@/pages/FeedbackPage'))
const StepLibraryPage = lazy(() => import('@/pages/StepLibraryPage'))
const ScriptLibraryPage = lazy(() => import('@/pages/ScriptLibraryPage'))
const ScriptManagePage = lazy(() => import('@/pages/ScriptManagePage'))
const AssistantChatPage = lazy(() => import('@/pages/AssistantChatPage'))
const KBAcceleratorPage = lazy(() => import('@/pages/KBAcceleratorPage'))
const GuidesHubPage = lazy(() => import('@/pages/GuidesHubPage'))
const GuideDetailPage = lazy(() => import('@/pages/GuideDetailPage'))
const AccountSettingsPage = lazy(() => import('@/pages/AccountSettingsPage'))
// Admin pages
const AdminLayout = lazy(() => import('@/components/admin/AdminLayout'))
const AdminDashboardPage = lazy(() => import('@/pages/admin/DashboardPage'))
const AdminUsersPage = lazy(() => import('@/pages/admin/UsersPage'))
const AdminUserDetailPage = lazy(() => import('@/pages/admin/UserDetailPage'))
const AdminInviteCodesPage = lazy(() => import('@/pages/admin/InviteCodesPage'))
const AdminAuditLogsPage = lazy(() => import('@/pages/admin/AuditLogsPage'))
const AdminPlanLimitsPage = lazy(() => import('@/pages/admin/PlanLimitsPage'))
const AdminFeatureFlagsPage = lazy(() => import('@/pages/admin/FeatureFlagsPage'))
const AdminSettingsPage = lazy(() => import('@/pages/admin/SettingsPage'))
const AdminGlobalCategoriesPage = lazy(() => import('@/pages/admin/GlobalCategoriesPage'))
const AdminSurveyInvitesPage = lazy(() => import('@/pages/admin/SurveyInvitesPage'))
const AdminSurveyResponsesPage = lazy(() => import('@/pages/admin/SurveyResponsesPage'))

// Account pages
const AccountLayout = lazy(() => import('@/components/account/AccountLayout'))
const ProfileSettingsPage = lazy(() => import('@/pages/account/ProfileSettingsPage'))
const TeamCategoriesPage = lazy(() => import('@/pages/account/TeamCategoriesPage'))
const TargetListsPage = lazy(() => import('@/pages/account/TargetListsPage'))
const ChatRetentionSettingsPage = lazy(() => import('@/pages/account/ChatRetentionSettingsPage'))
const IntegrationsPage = lazy(() => import('@/pages/account/IntegrationsPage'))

/** Wraps a lazy-loaded page with Suspense + ErrorBoundary */
function page(Component: React.LazyExoticComponent<React.ComponentType>) {
  return (
    <ErrorBoundary>
      <Suspense fallback={<PageLoader />}>
        <Component />
      </Suspense>
    </ErrorBoundary>
  )
}

export const router = sentryCreateBrowserRouter([
  {
    path: '/landing',
    element: page(LandingPage),
    errorElement: <RouteError />,
  },
  {
    path: '/login',
    element: <LoginPage />,
    errorElement: <RouteError />,
  },
  {
    path: '/register',
    element: <RegisterPage />,
    errorElement: <RouteError />,
  },
  {
    path: '/forgot-password',
    element: page(ForgotPasswordPage),
    errorElement: <RouteError />,
  },
  {
    path: '/reset-password',
    element: page(ResetPasswordPage),
    errorElement: <RouteError />,
  },
  {
    path: '/verify-email',
    element: page(VerifyEmailPage),
    errorElement: <RouteError />,
  },
  {
    path: '/survey',
    element: page(SurveyPage),
    errorElement: <RouteError />,
  },
  {
    path: '/survey/thank-you',
    element: page(SurveyThankYouPage),
    errorElement: <RouteError />,
  },
  {
    path: '/share/:shareToken',
    element: page(SharedSessionPage),
    errorElement: <RouteError />,
  },
  {
    path: '/change-password',
    element: (
      <ProtectedRoute>
        {page(ChangePasswordPage)}
      </ProtectedRoute>
    ),
    errorElement: <RouteError />,
  },
  {
    path: '/',
    element: (
      <ProtectedRoute>
        <AppLayout />
      </ProtectedRoute>
    ),
    errorElement: <RouteError />,
    children: [
      { index: true, element: page(QuickStartPage) },
      { path: 'trees', element: page(TreeLibraryPage) },
      { path: 'my-trees', element: page(MyTreesPage) },
      { path: 'trees/new', element: page(TreeEditorPage) },
      { path: 'trees/:id/edit', element: page(TreeEditorPage) },
      { path: 'flows/new', element: page(ProceduralEditorPage) },
      { path: 'flows/:id/edit', element: page(ProceduralEditorPage) },
      { path: 'flows/:id/navigate', element: page(ProceduralNavigationPage) },
      { path: 'flows/:id/maintenance', element: page(MaintenanceFlowDetailPage) },
      { path: 'flows/:id/batches/:batchId', element: page(BatchStatusPage) },
      { path: 'trees/:id/navigate', element: page(TreeNavigationPage) },
      { path: 'sessions', element: page(SessionHistoryPage) },
      { path: 'sessions/:id', element: page(SessionDetailPage) },
      { path: 'shares', element: page(MySharesPage) },
      { path: 'analytics', element: page(TeamAnalyticsPage) },
      { path: 'analytics/me', element: page(MyAnalyticsPage) },
      { path: 'feedback', element: page(FeedbackPage) },
      { path: 'step-library', element: page(StepLibraryPage) },
      { path: 'scripts', element: page(ScriptLibraryPage) },
      { path: 'scripts/manage', element: page(ScriptManagePage) },
      { path: 'kb-accelerator', element: page(KBAcceleratorPage) },
      { path: 'assistant', element: page(AssistantChatPage) },
      { path: 'guides', element: page(GuidesHubPage) },
      { path: 'guides/:slug', element: page(GuideDetailPage) },
      // Admin routes
      {
        path: 'admin',
        element: (
          <ErrorBoundary>
            <Suspense fallback={<PageLoader />}>
              <ProtectedRoute requiredRole="super_admin">
                <AdminLayout />
              </ProtectedRoute>
            </Suspense>
          </ErrorBoundary>
        ),
        children: [
          { index: true, element: page(AdminDashboardPage) },
          { path: 'users', element: page(AdminUsersPage) },
          { path: 'users/:userId', element: page(AdminUserDetailPage) },
          { path: 'invite-codes', element: page(AdminInviteCodesPage) },
          { path: 'audit-logs', element: page(AdminAuditLogsPage) },
          { path: 'plan-limits', element: page(AdminPlanLimitsPage) },
          { path: 'feature-flags', element: page(AdminFeatureFlagsPage) },
          { path: 'settings', element: page(AdminSettingsPage) },
          { path: 'categories', element: page(AdminGlobalCategoriesPage) },
          { path: 'survey-invites', element: page(AdminSurveyInvitesPage) },
          { path: 'survey-responses', element: page(AdminSurveyResponsesPage) },
        ],
      },
      // Account routes
      {
        path: 'account',
        element: (
          <ErrorBoundary>
            <Suspense fallback={<PageLoader />}>
              <AccountLayout />
            </Suspense>
          </ErrorBoundary>
        ),
        children: [
          { index: true, element: page(AccountSettingsPage) },
          { path: 'profile', element: page(ProfileSettingsPage) },
          {
            path: 'categories',
            element: (
              <ProtectedRoute requiredRole="owner">
                {page(TeamCategoriesPage)}
              </ProtectedRoute>
            ),
          },
          {
            path: 'chat-retention',
            element: (
              <ProtectedRoute requiredRole="owner">
                {page(ChatRetentionSettingsPage)}
              </ProtectedRoute>
            ),
          },
          { path: 'target-lists', element: page(TargetListsPage) },
          {
            path: 'integrations',
            element: (
              <ProtectedRoute requiredRole="owner">
                {page(IntegrationsPage)}
              </ProtectedRoute>
            ),
          },
        ],
      },
    ],
  },
])

export default router
