'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

export function withAdminAuth<T extends object>(WrappedComponent: React.ComponentType<T>) {
  return function AdminProtectedComponent(props: T) {
    const [isLoading, setIsLoading] = useState(true)
    const [isAuthorized, setIsAuthorized] = useState(false)
    const router = useRouter()

    useEffect(() => {
      const checkAuth = () => {
        const token = localStorage.getItem('token')
        const user = localStorage.getItem('user')

        if (!token || !user) {
          router.push('/login')
          return
        }

        try {
          const userData = JSON.parse(user)
          if (!userData.isAdmin) {
            router.push('/')
            return
          }

          setIsAuthorized(true)
        } catch (error) {
          router.push('/login')
          return
        } finally {
          setIsLoading(false)
        }
      }

      checkAuth()
    }, [router])

    if (isLoading) {
      return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      )
    }

    if (!isAuthorized) {
      return null
    }

    return <WrappedComponent {...props} />
  }
}
