import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useEffect, type ReactNode } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AppShell } from './layout/AppShell';
import { AuthGate } from './auth/AuthGate';
import { PlatformErrorBoundary, RoutePage } from './routing/RouteBoundary';
import { RoutePageFactories, RoutePages } from './routing/routeModules';
import { ROUTER_FUTURE } from './routing/routerConfig';
import { QUERY_MEMORY } from './queryPolicy';
import { usePlatformSession } from './auth/AuthGate';
import { hasMenu } from './auth/session';

export function createPlatformQueryClient() {
  return new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 15_000,
        gcTime: 5 * 60_000,
        retry: 1,
        refetchOnWindowFocus: false
      },
      mutations: {
        gcTime: QUERY_MEMORY.highVolumeGcTime,
        retry: 0
      }
    }
  });
}

const queryClient = createPlatformQueryClient();
export const PLATFORM_READY_EVENT = 'vehicle-platform:ready';

function PlatformReadySignal() {
  useEffect(() => {
    window.dispatchEvent(new Event(PLATFORM_READY_EVENT));
  }, []);
  return null;
}

function defaultPath(menuKeys: string[]) {
  const first = ['monitor', 'vehicles', 'tracks', 'statistics'].find((key) => menuKeys.includes(key));
  return first ? `/${first}` : '/monitor';
}

function ProtectedRoute({ menu, children }: { menu: string; children: ReactNode }) {
  const { session } = usePlatformSession();
  if (!hasMenu(session, menu)) return <Navigate to={defaultPath(session.menuKeys ?? [])} replace />;
  return children;
}

export function AppV2() {
  return (
    <QueryClientProvider client={queryClient}>
      <PlatformReadySignal />
      <PlatformErrorBoundary>
        <AuthGate><BrowserRouter future={ROUTER_FUTURE}>
          <Routes>
            <Route element={<AppShell />}>
              <Route index element={<SessionIndex />} />
              <Route path="/monitor" element={<ProtectedRoute menu="monitor"><RoutePage page={RoutePages.Monitor} recreatePage={RoutePageFactories.Monitor} label="全局监控" /></ProtectedRoute>} />
              <Route path="/vehicles/:vin?" element={<ProtectedRoute menu="vehicles"><RoutePage page={RoutePages.Vehicles} recreatePage={RoutePageFactories.Vehicles} label="车辆查询" /></ProtectedRoute>} />
              <Route path="/tracks" element={<ProtectedRoute menu="tracks"><RoutePage page={RoutePages.Tracks} recreatePage={RoutePageFactories.Tracks} label="轨迹回放" /></ProtectedRoute>} />
              <Route path="/history" element={<ProtectedRoute menu="history"><RoutePage page={RoutePages.History} recreatePage={RoutePageFactories.History} label="历史数据" /></ProtectedRoute>} />
              <Route path="/statistics" element={<ProtectedRoute menu="statistics"><RoutePage page={RoutePages.Statistics} recreatePage={RoutePageFactories.Statistics} label="里程查询" /></ProtectedRoute>} />
              <Route path="/access" element={<ProtectedRoute menu="access"><RoutePage page={RoutePages.Access} recreatePage={RoutePageFactories.Access} label="接入管理" /></ProtectedRoute>} />
              <Route path="/alerts/*" element={<ProtectedRoute menu="alerts"><RoutePage page={RoutePages.Alerts} recreatePage={RoutePageFactories.Alerts} label="告警中心" /></ProtectedRoute>} />
              <Route path="/operations" element={<ProtectedRoute menu="operations"><RoutePage page={RoutePages.Operations} recreatePage={RoutePageFactories.Operations} label="运维质量" /></ProtectedRoute>} />
              <Route path="/users" element={<ProtectedRoute menu="users"><RoutePage page={RoutePages.Users} recreatePage={RoutePageFactories.Users} label="账号管理" /></ProtectedRoute>} />
              <Route path="*" element={<Navigate to="/monitor" replace />} />
            </Route>
          </Routes>
        </BrowserRouter></AuthGate>
      </PlatformErrorBoundary>
    </QueryClientProvider>
  );
}

function SessionIndex() {
  const { session } = usePlatformSession();
  return <Navigate to={defaultPath(session.menuKeys ?? [])} replace />;
}
