import React, { createContext, useState, useEffect } from 'react'
import api from '../api'

export const AuthContext = createContext()

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const [token, setToken] = useState(localStorage.getItem('token'))
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (token) {
      localStorage.setItem('token', token)
      fetchUserData()
    } else {
      localStorage.removeItem('token')
      setLoading(false)
    }
  }, [token])

  const fetchUserData = async () => {
    try {
      const response = await api.get('/users/me')
      setUser(response.data)
    } catch (error) {
      console.error('Error fetching user data:', error)
      // If token is invalid, clear it
      setToken(null)
      setUser(null)
    } finally {
      setLoading(false)
    }
  }

  const logout = () => {
    setUser(null)
    setToken(null)
    localStorage.removeItem('token')
  }

  return (
    <AuthContext.Provider value={{ user, setUser, token, setToken, loading, setLoading, logout }}>
      {!loading && children}
    </AuthContext.Provider>
  )
}
