import { Navigate, useLocation } from "react-router-dom"
import { useContext, useEffect, useState } from "react"
import { AuthContext } from "@/contexts/AuthContext"

export function RequireAuth({ children }: { children: React.ReactNode }) {
  const isLoggedIn = sessionStorage.getItem("isLoggedIn") === "true"
  const { token, user, fetchCurrentUser } = useContext(AuthContext)
  const location = useLocation()
  const [isLoading, setIsLoading] = useState(!!token && !user)

  // This will make sure the user data is loaded the first time
  useEffect(() => {
    const loadUserData = async () => {
      if (token && !user) {
        setIsLoading(true)
        try {
          await fetchCurrentUser()
        } catch (error) {
          console.error("Failed to fetch user data:", error)
        } finally {
          setIsLoading(false)
        }
      }
    }
    
    loadUserData()
  }, [token, user, fetchCurrentUser])

  // Check if token exists but we're not logged in
  useEffect(() => {
    if (token && !isLoggedIn) {
      // Verify the token and fetch user data
      fetchCurrentUser().catch(() => {
        // Do nothing - the AuthContext will handle errors
      })
    }
  }, [token, isLoggedIn, fetchCurrentUser])

  // If still loading user data, show nothing yet
  if (isLoading) {
    return <div className="p-8 flex justify-center items-center h-screen">Loading...</div>
  }

  if (!isLoggedIn) {
    // Redirect to login with the current path in the redirect parameter
    return <Navigate 
      to={`/login?redirect=${encodeURIComponent(location.pathname + location.search)}`} 
      replace 
    />
  }

  return <>{children}</>
} 