import { createContext, useContext, useState, useEffect } from 'react'

const AuthContext = createContext({
  user: null,
  token: null,
  setUser: () => {},
  setToken: () => {},
  isAuthenticated: false
})

export const AuthContextProvider = ({ children }) => {
  // Initialiser avec null explicitement
  const [user, setUser] = useState(null)
  const [token, _setToken] = useState(null)
  const [isLoading, setIsLoading] = useState(true)

  // Initialiser depuis localStorage au montage
  useEffect(() => {
    const storedToken = localStorage.getItem('ACCESS_TOKEN')
    const storedUser = localStorage.getItem('USER_DATA')
    
    if (storedToken) {
      _setToken(storedToken)
    }
    
    if (storedUser) {
      try {
        setUser(JSON.parse(storedUser))
      } catch (error) {
        console.error('Erreur parsing user data:', error)
        localStorage.removeItem('USER_DATA')
      }
    }
    
    setIsLoading(false)
  }, [])

  const setToken = (newToken) => {
    _setToken(newToken)
    
    if (newToken) {
      localStorage.setItem('ACCESS_TOKEN', newToken)
    } else {
      localStorage.removeItem('ACCESS_TOKEN')
      localStorage.removeItem('USER_DATA') // Nettoyer aussi les données utilisateur
      setUser(null) // Reset user state
    }
  }

  const setUserData = (userData) => {
    setUser(userData)
    
    if (userData) {
      localStorage.setItem('USER_DATA', JSON.stringify(userData))
    } else {
      localStorage.removeItem('USER_DATA')
    }
  }

  const logout = () => {
    setToken(null)
    setUserData(null)
  }

  const isAuthenticated = !!(token && user)

  const contextValue = {
    user,
    token,
    setUser: setUserData,
    setToken,
    logout,
    isAuthenticated,
    isLoading
  }

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

export const useAuthContext = () => useContext(AuthContext)