import { createBrowserRouter, Navigate } from 'react-router';
import { ProtectedRoute } from './auth/ProtectedRoute';
import { RequireAdmin } from './auth/RequireAdmin';
import { LoginPage } from './auth/LoginPage';
import { OidcCallback } from './auth/OidcCallback';
import { LayoutShell } from './components/LayoutShell';
import { config } from './config';
import { lazy, Suspense } from 'react';
import { PageLoader } from './components/PageLoader';

const ExchangesPage = lazy(() => import('./pages/Exchanges/ExchangesPage'));
const DashboardPage = lazy(() => import('./pages/DashboardTab/DashboardPage'));
const RuntimePage = lazy(() => import('./pages/RuntimeTab/RuntimePage'));
const AdminLayout = lazy(() => import('./pages/Admin/AdminLayout'));
const RbacPage = lazy(() => import('./pages/Admin/RbacPage'));
const AuditLogPage = lazy(() => import('./pages/Admin/AuditLogPage'));
const OidcConfigPage = lazy(() => import('./pages/Admin/OidcConfigPage'));
const DatabaseAdminPage = lazy(() => import('./pages/Admin/DatabaseAdminPage'));
const ClickHouseAdminPage = lazy(() => import('./pages/Admin/ClickHouseAdminPage'));
const ServerMetricsAdminPage = lazy(() => import('./pages/Admin/ServerMetricsAdminPage'));
const EnvironmentsPage = lazy(() => import('./pages/Admin/EnvironmentsPage'));
const OutboundConnectionsPage = lazy(() => import('./pages/Admin/OutboundConnectionsPage'));
const OutboundConnectionEditor = lazy(() => import('./pages/Admin/OutboundConnectionEditor'));
const SensitiveKeysPage = lazy(() => import('./pages/Admin/SensitiveKeysPage'));
const AppsTab = lazy(() => import('./pages/AppsTab/AppsTab'));
const AppDeploymentPage = lazy(() => import('./pages/AppsTab/AppDeploymentPage'));
const SwaggerPage = lazy(() => import('./pages/Swagger/SwaggerPage'));
const InboxPage        = lazy(() => import('./pages/Alerts/InboxPage'));
const RulesListPage    = lazy(() => import('./pages/Alerts/RulesListPage'));
const RuleEditorWizard = lazy(() => import('./pages/Alerts/RuleEditor/RuleEditorWizard'));
const SilencesPage     = lazy(() => import('./pages/Alerts/SilencesPage'));

function SuspenseWrapper({ children }: { children: React.ReactNode }) {
  return (
    <Suspense fallback={<PageLoader />}>
      {children}
    </Suspense>
  );
}

const basename = config.basePath.replace(/\/$/, '') || undefined;

export const router = createBrowserRouter([
  { path: '/login', element: <LoginPage /> },
  { path: '/oidc/callback', element: <OidcCallback /> },
  {
    element: <ProtectedRoute />,
    children: [
      {
        element: <LayoutShell />,
        children: [
          // Default redirect
          { index: true, element: <Navigate to="/exchanges" replace /> },

          // Exchanges tab
          { path: 'exchanges', element: <SuspenseWrapper><ExchangesPage /></SuspenseWrapper> },
          { path: 'exchanges/:appId', element: <SuspenseWrapper><ExchangesPage /></SuspenseWrapper> },
          { path: 'exchanges/:appId/:routeId', element: <SuspenseWrapper><ExchangesPage /></SuspenseWrapper> },
          { path: 'exchanges/:appId/:routeId/:exchangeId', element: <SuspenseWrapper><ExchangesPage /></SuspenseWrapper> },

          // Dashboard tab
          { path: 'dashboard', element: <SuspenseWrapper><DashboardPage /></SuspenseWrapper> },
          { path: 'dashboard/:appId', element: <SuspenseWrapper><DashboardPage /></SuspenseWrapper> },
          { path: 'dashboard/:appId/:routeId', element: <SuspenseWrapper><DashboardPage /></SuspenseWrapper> },

          // Runtime tab
          { path: 'runtime', element: <SuspenseWrapper><RuntimePage /></SuspenseWrapper> },
          { path: 'runtime/:appId', element: <SuspenseWrapper><RuntimePage /></SuspenseWrapper> },
          { path: 'runtime/:appId/:instanceId', element: <SuspenseWrapper><RuntimePage /></SuspenseWrapper> },

          // Redirects for removed tabs
          { path: 'logs', element: <Navigate to="/runtime" replace /> },
          { path: 'logs/:appId', element: <Navigate to="/runtime" replace /> },
          { path: 'logs/:appId/:routeId', element: <Navigate to="/runtime" replace /> },
          { path: 'config', element: <Navigate to="/apps" replace /> },
          { path: 'config/:appId', element: <Navigate to="/apps" replace /> },
          { path: 'deployments', element: <Navigate to="/apps" replace /> },

          // Apps tab (OPERATOR+ via UI guard, shows all or single app)
          { path: 'apps', element: <SuspenseWrapper><AppsTab /></SuspenseWrapper> },
          { path: 'apps/new', element: <SuspenseWrapper><AppDeploymentPage /></SuspenseWrapper> },
          { path: 'apps/:appId', element: <SuspenseWrapper><AppDeploymentPage /></SuspenseWrapper> },

          // Alerts
          { path: 'alerts', element: <Navigate to="/alerts/inbox" replace /> },
          { path: 'alerts/inbox',     element: <SuspenseWrapper><InboxPage /></SuspenseWrapper> },
          { path: 'alerts/rules',     element: <SuspenseWrapper><RulesListPage /></SuspenseWrapper> },
          { path: 'alerts/rules/new', element: <SuspenseWrapper><RuleEditorWizard /></SuspenseWrapper> },
          { path: 'alerts/rules/:id', element: <SuspenseWrapper><RuleEditorWizard /></SuspenseWrapper> },
          { path: 'alerts/silences',  element: <SuspenseWrapper><SilencesPage /></SuspenseWrapper> },

          // Admin (ADMIN role required)
          {
            element: <RequireAdmin />,
            children: [{
              path: 'admin',
              element: <SuspenseWrapper><AdminLayout /></SuspenseWrapper>,
              children: [
                { index: true, element: <Navigate to="/admin/rbac" replace /> },
                { path: 'rbac', element: <SuspenseWrapper><RbacPage /></SuspenseWrapper> },
                { path: 'audit', element: <SuspenseWrapper><AuditLogPage /></SuspenseWrapper> },
                { path: 'oidc', element: <SuspenseWrapper><OidcConfigPage /></SuspenseWrapper> },
                { path: 'outbound-connections', element: <SuspenseWrapper><OutboundConnectionsPage /></SuspenseWrapper> },
                { path: 'outbound-connections/new', element: <SuspenseWrapper><OutboundConnectionEditor /></SuspenseWrapper> },
                { path: 'outbound-connections/:id', element: <SuspenseWrapper><OutboundConnectionEditor /></SuspenseWrapper> },
                { path: 'sensitive-keys', element: <SuspenseWrapper><SensitiveKeysPage /></SuspenseWrapper> },
                { path: 'database', element: <SuspenseWrapper><DatabaseAdminPage /></SuspenseWrapper> },
                { path: 'clickhouse', element: <SuspenseWrapper><ClickHouseAdminPage /></SuspenseWrapper> },
                { path: 'server-metrics', element: <SuspenseWrapper><ServerMetricsAdminPage /></SuspenseWrapper> },
                { path: 'environments', element: <SuspenseWrapper><EnvironmentsPage /></SuspenseWrapper> },
              ],
            }],
          },
          { path: 'api-docs', element: <SuspenseWrapper><SwaggerPage /></SuspenseWrapper> },
        ],
      },
    ],
  },
], { basename });
