import React, { createContext, useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import type { AuthContextType, AuthState } from '../types'
import type { AuthManager } from '../core'

export const AuthContext = createContext<AuthContextType | null>(null)

interface AuthProviderProps {
  children: ReactNode
  authManager: AuthManager
}

export function AuthProvider({ children, authManager }: AuthProviderProps) {
  const [state, setState] = useState<AuthState>(authManager.getState())

  useEffect(() => {
    const unsubscribe = authManager.onAuthStateChange(setState)
    return unsubscribe
  }, [authManager])

  const contextValue: AuthContextType = {
    state,
    signIn: authManager.signIn.bind(authManager),
    signUp: authManager.signUp.bind(authManager),
    signOut: authManager.signOut.bind(authManager),
    resetPassword: authManager.resetPassword.bind(authManager),
    updatePassword: authManager.updatePassword.bind(authManager),
    refreshSession: authManager.refreshSession.bind(authManager),
    hasPermission: authManager.hasPermission.bind(authManager),
    hasRole: authManager.hasRole.bind(authManager),
    requireAuth: authManager.requireAuth.bind(authManager),
    requireRole: authManager.requireRole.bind(authManager),
  }

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  )
}