import { useEffect, useState } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { Loader2 } from 'lucide-react'
import { api, UserInfo } from '@/lib/api'
import { clearAuth, RoleName } from '@/lib/auth'

interface AuthGuardProps {
  children: React.ReactNode
  allowedRoles?: RoleName[]
  requireAuth?: boolean
}

export function AuthGuard({ children, allowedRoles, requireAuth = true }: AuthGuardProps) {
  const location = useLocation()
  const [user, setUser] = useState<UserInfo | null | undefined>(undefined)

  useEffect(() => {
    const token = localStorage.getItem('access_token')
    if (!token) {
      setUser(null)
      return
    }
    api.me()
      .then(setUser)
      .catch(() => {
        clearAuth()
        setUser(null)
      })
  }, [location.pathname])

  if (user === undefined) {
    return (
      <div className="h-screen w-full flex items-center justify-center bg-base text-foreground">
        <Loader2 className="h-6 w-6 animate-spin text-accent" />
      </div>
    )
  }

  if (requireAuth && !user) {
    return <Navigate to="/login" state={{ from: location.pathname }} replace />
  }

  if (allowedRoles && user && !allowedRoles.includes(user.role)) {
    return <Navigate to="/" replace />
  }

  return <>{children}</>
}
