import React, { Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Spin } from 'antd';
import MainLayout from '@/components/Layout/MainLayout';
import { routes } from '@/config/routes';
import Login from '@/pages/auth/Login';
import NotFound from '@/pages/notFound';
import Dashboard from '@/pages/Dashboard';
import { ProtectedRoute } from '@/components/auth/ProtectedRoute';
import { useAuth } from '@/contexts/AuthContext';

const LoadingComponent = () => (
  <div className="flex justify-center items-center min-h-[200px]">
    <Spin size="large" />
  </div>
);
// 这里做premeision 路由限制
const renderRoutes = (routes) => {
  return routes
    // .filter(route => !route.hidden)
    .map(route => {
      const Component = route.component;
      if (route.children) {
        return (
          <Route key={route.path} path={route.path} element={
            <Suspense fallback={<LoadingComponent />}>
              <Component />
            </Suspense>
          }>
            {renderRoutes(route.children)}
          </Route>
        );
      }

      return (
        <Route
          key={route.path}
          path={route.path}
          element={
            <Suspense fallback={<LoadingComponent />}>
              <Component />
            </Suspense>
          }
        />
      );
    });
};

const AppRoutes = () => {
  const { user } = useAuth();

  return (
    <Routes>
      {/* 公开路由 */}
      <Route 
        path="/login" 
        element={
          user ? <Navigate to="/dashboard" replace /> : <Login />
        } 
      />
      
      {/* 受保护的路由 */}
      <Route
        path="/"
        element={
          <ProtectedRoute>
            <MainLayout />
          </ProtectedRoute>
        }
      >
        <Route 
          path="dashboard" 
          element={
            <Suspense fallback={<LoadingComponent />}>
              <Dashboard />
            </Suspense>
          } 
        />
        {renderRoutes(routes)}
        <Route index element={<Navigate to="/dashboard" replace />} />
        <Route path="*" element={<NotFound />} />
      </Route>
    </Routes>
  );
};

export default AppRoutes;