import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { adminService } from '../services/adminService'

interface AdminAuthContextType {
  isAuthenticated: boolean
  isAdmin: boolean
  isLoading: boolean
  signIn: (email: string, password: string) => Promise<void>
  signOut: () => Promise<void>
}

const AdminAuthContext = createContext<AdminAuthContextType | undefined>(undefined)

export function AdminAuthProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isAdmin, setIsAdmin] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

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

  async function checkAuth() {
    try {
      const user = await adminService.getCurrentUser()
      if (user) {
        setIsAuthenticated(true)
        const adminStatus = await adminService.isAdmin()
        setIsAdmin(adminStatus)
      }
    } catch (error) {
      console.error('Auth check failed:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const signIn = async (email: string, password: string) => {
    await adminService.signIn(email, password)
    setIsAuthenticated(true)
    const adminStatus = await adminService.isAdmin()
    setIsAdmin(adminStatus)
  }

  const signOut = async () => {
    await adminService.signOut()
    setIsAuthenticated(false)
    setIsAdmin(false)
  }

  return (
    <AdminAuthContext.Provider value={{ isAuthenticated, isAdmin, isLoading, signIn, signOut }}>
      {children}
    </AdminAuthContext.Provider>
  )
}

export function useAdminAuth() {
  const context = useContext(AdminAuthContext)
  if (context === undefined) {
    throw new Error('useAdminAuth must be used within an AdminAuthProvider')
  }
  return context
}
