import React, { useEffect } from 'react';
import { useNavigate } from 'react-router';
import { useAuth } from '@d8d/tenant-management-ui';
import { Skeleton } from '@/client/components/ui/skeleton';

export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { isAuthenticated, isLoading } = useAuth();
  const navigate = useNavigate();
  
  useEffect(() => {
    // 只有在加载完成且未认证时才重定向
    if (!isLoading && !isAuthenticated) {
      navigate('/tenant/login', { replace: true });
    }
  }, [isAuthenticated, isLoading, navigate]);
  
  // 显示加载状态，直到认证检查完成
  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="space-y-2">
          <Skeleton className="h-12 w-12 rounded-full" />
          <div className="space-y-2">
            <Skeleton className="h-4 w-[250px]" />
            <Skeleton className="h-4 w-[200px]" />
          </div>
        </div>
      </div>
    );
  }
  
  // 如果未认证且不再加载中，不显示任何内容（等待重定向）
  if (!isAuthenticated) {
    return null;
  }
  
  return children;
};