import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { CircularProgress, Box } from '@mui/material';
import UserDataProvider from './Provider/UserDataProvider';

interface AuthGuardProps {
  children: React.ReactNode;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const location = useLocation();
  const navigate = useNavigate();
  
  // 直接从localStorage检查token，避免React状态更新的延迟
  const authorization = localStorage.getItem('Authorization');
  const isAuthenticated = !!authorization;
  const isLoginPage = location.pathname === '/login';

  useEffect(() => {
    if (isAuthenticated && isLoginPage) {
      // 已登录用户访问登录页，重定向到首页
      navigate('/', { replace: true });
    } else if (!isAuthenticated && !isLoginPage) {
      // 未登录用户访问其他页面，重定向到登录页并保存当前路径
      const redirectUrl = encodeURIComponent(location.pathname + location.search);
      navigate(`/login?redirect=${redirectUrl}`, { replace: true });
    }
  }, [isAuthenticated, isLoginPage, location, navigate]);

  // 如果是登录页面，直接渲染
  if (isLoginPage) {
    return <>{children}</>;
  }

  // 如果未认证，显示加载状态（实际上会被重定向）
  if (!isAuthenticated) {
    return (
      <Box 
        display="flex" 
        justifyContent="center" 
        alignItems="center" 
        minHeight="100vh"
      >
        <CircularProgress />
      </Box>
    );
  }

  // 已认证，渲染子组件
  return (
    <UserDataProvider>
      {children}
    </UserDataProvider>
  );
};

export default AuthGuard;