import { BrowserRouter, Routes, Route, Navigate, useParams, Outlet } from 'react-router-dom'
import { ConfigProvider } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import Login from '@/pages/Login/Login'
import ProjectList from '@/pages/ProjectList/ProjectList'
import DocumentPage from '@/pages/Document/DocumentPage'
import DocumentEditor from '@/pages/Document/DocumentEditor'
import Dashboard from '@/pages/Dashboard'
import Desktop from '@/pages/Desktop'
import Constructing from '@/pages/Constructing'
import PreviewPage from '@/pages/Preview/PreviewPage'
import ProfilePage from '@/pages/Profile/ProfilePage'
import Permissions from '@/pages/System/Permissions'
import Users from '@/pages/System/Users'
import Roles from '@/pages/System/Roles'
import SystemLogs from '@/pages/SystemLogs/SystemLogs'
import NotificationList from '@/pages/Notifications/NotificationList'
import ProtectedRoute from '@/components/ProtectedRoute'
import MainLayout from '@/components/MainLayout/MainLayout'
import '@/App.css'

// 重定向到文档页面的组件
function RedirectToDocs() {
  const { projectId } = useParams()
  return <Navigate to={`/projects/${projectId}/docs`} replace />
}

// 共享布局的包装组件
function LayoutWrapper() {
  return (
    <MainLayout>
      <Outlet />
    </MainLayout>
  )
}

function App() {
  return (
    <ConfigProvider locale={zhCN}>
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
          {/* 项目预览（公开访问，无需登录） */}
          <Route path="/preview/:projectId" element={<PreviewPage />} />

          {/* 使用共享布局的路由 */}
          <Route element={<ProtectedRoute><LayoutWrapper /></ProtectedRoute>}>
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/desktop" element={<Desktop />} />
            <Route path="/projects" element={<Navigate to="/projects/my" replace />} />
            <Route path="/projects/my" element={<ProjectList type="my" />} />
            <Route path="/projects/share" element={<ProjectList type="share" />} />
            <Route path="/projects/:projectId/docs" element={<DocumentPage />} />
            <Route path="/projects/:projectId/editor" element={<DocumentEditor />} />
            <Route path="/projects/:projectId/*" element={<RedirectToDocs />} />
            <Route path="/constructing" element={<Constructing />} />
            <Route path="/profile" element={<ProfilePage />} />
            <Route path="/notifications" element={<NotificationList />} />
            <Route path="/system/permissions" element={<Permissions />} />
            <Route path="/system/users" element={<Users />} />
            <Route path="/system/roles" element={<Roles />} />
            <Route path="/system/logs" element={<SystemLogs />} />
          </Route>

          <Route path="/" element={<Navigate to="/projects" replace />} />
        </Routes>
      </BrowserRouter>
    </ConfigProvider>
  )
}

export default App
