'use client'

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

interface AdminUser {
  id: string
  name: string
  email: string
  role: 'ADMIN' | 'SUPERADMIN'
  isActive: boolean
}

export function useAdminAuth() {
  const router = useRouter()
  const [user, setUser] = useState<AdminUser | null>(null)
  const [loading, setLoading] = useState(true)
  const [isAuthenticated, setIsAuthenticated] = useState(false)

  useEffect(() => {
    checkAuth()
  }, [])

  const checkAuth = () => {
    try {
      const token = localStorage.getItem('adminToken')
      const userData = localStorage.getItem('adminUser')

      if (!token || !userData) {
        logout()
        return
      }

      const parsedUser = JSON.parse(userData)
      
      // Validate token format (basic check)
      if (typeof token !== 'string' || token.length < 10) {
        logout()
        return
      }

      setUser(parsedUser)
      setIsAuthenticated(true)
    } catch (error) {
      console.error('Auth check error:', error)
      logout()
    } finally {
      setLoading(false)
    }
  }

  const logout = () => {
    localStorage.removeItem('adminToken')
    localStorage.removeItem('adminUser')
    setUser(null)
    setIsAuthenticated(false)
    router.push('/admin/login')
  }

  const login = (token: string, userData: AdminUser) => {
    localStorage.setItem('adminToken', token)
    localStorage.setItem('adminUser', JSON.stringify(userData))
    setUser(userData)
    setIsAuthenticated(true)
  }

  const getAuthHeaders = (contentType: 'json' | 'formData' = 'json') => {
    const token = localStorage.getItem('adminToken')
    const headers: Record<string, string> = {
      'Authorization': `Bearer ${token}`
    }
    
    if (contentType === 'json') {
      headers['Content-Type'] = 'application/json'
    }
    
    return headers
  }

  return {
    user,
    loading,
    isAuthenticated,
    logout,
    login,
    checkAuth,
    getAuthHeaders
  }
}