"use client"

import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/hooks/use-auth"

interface AuthGuardProps {
  children: React.ReactNode
  requiredRole?: "admin" | "voter" | "superadmin"
}

export function AuthGuard({ children, requiredRole }: AuthGuardProps) {
  const { user, loading, isAuthenticated, isAdmin, isVoter, isSuperAdmin } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (!loading) {
      // If not authenticated, redirect to login
      if (!isAuthenticated) {
        router.push("/login")
        return
      }

      // If role is required, check if user has the required role
      if (requiredRole && requiredRole === "admin" && !isAdmin) {
        router.push("/login")
        return
      }

      if (requiredRole && requiredRole === "voter" && !isVoter) {
        router.push("/login")
        return
      }

      if (requiredRole && requiredRole === "superadmin" && !isSuperAdmin) {
        router.push("/login")
        return
      }
    }
  }, [loading, isAuthenticated, isAdmin, isVoter, isSuperAdmin, requiredRole, router])

  // Show loading while checking authentication
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  // If not authenticated, don't render children (will redirect)
  if (!isAuthenticated) {
    return null
  }

  // If role requirements not met, don't render children (will redirect)
  if (requiredRole === "admin" && !isAdmin) {
    return null
  }

  if (requiredRole === "voter" && !isVoter) {
    return null
  }

  if (requiredRole === "superadmin" && !isSuperAdmin) {
    return null
  }

  // All checks passed, render children
  return <>{children}</>
}
