import { lazy, Suspense } from "react";
import { Navigate, Route, Routes } from "react-router-dom";

import LoadingScreen from "@/components/LoadingScreen";
import MainLayout from "@/layouts/MainLayout";
import ProtectedRoute from "@/routes/ProtectedRoute";
import { hasAccessToken } from "@/utils/auth";

const LoginPage = lazy(() => import("@/pages/login"));
const ForgotPasswordPage = lazy(() => import("@/pages/forgot-password"));
const MeetingsPage = lazy(() => import("@/pages/meetings"));
const MeetingDetailPage = lazy(() => import("@/pages/meeting-detail"));
const MeetingPreviewPage = lazy(() => import("@/pages/meeting-preview"));
const ProfilePage = lazy(() => import("@/pages/profile"));
const PasswordPage = lazy(() => import("@/pages/password"));
const ScanConfirmPage = lazy(() => import("@/pages/scan-confirm"));

function HomeRedirect() {
  return <Navigate to={hasAccessToken() ? "/meetings" : "/login"} replace />;
}

export default function App() {
  return (
    <Suspense fallback={<LoadingScreen text="页面加载中..." />}>
      <Routes>
        <Route path="/" element={<HomeRedirect />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/forgot-password" element={<ForgotPasswordPage/>}/>
        <Route path="/meetings/:id/preview" element={<MeetingPreviewPage />} />

        <Route
          path="/meetings"
          element={
            <ProtectedRoute>
              <MainLayout activeTab="meetings">
                <MeetingsPage />
              </MainLayout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/meetings/:id"
          element={
            <ProtectedRoute>
              <MainLayout>
                <MeetingDetailPage />
              </MainLayout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/profile"
          element={
            <ProtectedRoute>
              <MainLayout activeTab="profile">
                <ProfilePage />
              </MainLayout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/profile/password"
          element={
            <ProtectedRoute>
              <MainLayout>
                <PasswordPage />
              </MainLayout>
            </ProtectedRoute>
          }
        />
        <Route
          path="/scan-confirm/:sessionId"
          element={
            <ProtectedRoute>
              <MainLayout>
                <ScanConfirmPage />
              </MainLayout>
            </ProtectedRoute>
          }
        />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Suspense>
  );
}
