import React, { useState, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';

export function ProtectedRoute({ children }) {
    const [isLoading, setIsLoading] = useState(true);
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const location = useLocation();

    useEffect(() => {
        // Check for the access token in local storage
        const token = localStorage.getItem('accessToken');
        
        // Add a small delay to ensure localStorage is available
        const checkAuth = () => {
            if (token) {
                setIsAuthenticated(true);
            } else {
                setIsAuthenticated(false);
            }
            setIsLoading(false);
        };

        // Use setTimeout to ensure localStorage is ready
        const timer = setTimeout(checkAuth, 100);
        
        return () => clearTimeout(timer);
    }, []);

    // Show loading state while checking authentication
    if (isLoading) {
        return (
            <div className="flex items-center justify-center min-h-screen bg-gray-50">
                <div className="text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                    <p className="text-gray-600">Loading...</p>
                </div>
            </div>
        );
    }

    // If not authenticated, redirect to login
    if (!isAuthenticated) {
        // We pass the original location they tried to visit, so we can redirect them back after login
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    // If authenticated, render the child components (the protected page)
    return children;
}