import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import { 
  type User, 
  refreshToken,
  logout as apiLogout
} from '../api/auth'
import { setAuthToken } from '../api/token'

interface AuthContextType {
  user: User | null
  isAuthenticated: boolean
  isLoading: boolean
  login: (token: string, user: User) => void
  logout: () => void
  updateUser: (user: User) => void
}

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

export function useAuth() {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

interface AuthProviderProps {
  children: ReactNode
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  const isAuthenticated = !!user

  // Initialize auth on app start
  useEffect(() => {
    let mounted = true

    async function initAuth() {
      try {
        // Try to refresh token first (cookie-based)
        const authResponse = await refreshToken()
        if (mounted && authResponse?.access_token) {
          setAuthToken(authResponse.access_token)
          setUser(authResponse.user)
        }
      } catch {
        // No valid session — that's fine, app works without auth
        if (mounted) {
          setAuthToken(null)
          setUser(null)
        }
      } finally {
        if (mounted) {
          setIsLoading(false)
        }
      }
    }

    initAuth()

    return () => {
      mounted = false
    }
  }, [])

  const login = (token: string, userData: User) => {
    setAuthToken(token)
    setUser(userData)
  }

  const logout = async () => {
    try {
      await apiLogout()
    } catch (error) {
      // Ignore logout API errors
      console.warn('Logout API call failed:', error)
    } finally {
      setAuthToken(null)
      setUser(null)
    }
  }

  const updateUser = (userData: User) => {
    setUser(userData)
  }

  return (
    <AuthContext.Provider 
      value={{ 
        user, 
        isAuthenticated, 
        isLoading, 
        login, 
        logout, 
        updateUser 
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}