import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import { api } from '@/lib/api'
import type { AuthContextType, User, LoginRequest, RegisterRequest } from '@/types/auth'

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 [loading, setLoading] = useState(true)

  useEffect(() => {
    const initAuth = async () => {
      try {
        // Try to get user info using cookies
        const user = await api.auth.getMe()
        setUser(user)
      } catch {
        // User is not authenticated - this is normal for logged out users
      }
      setLoading(false)
    }

    initAuth()
  }, [])

  const login = async (credentials: LoginRequest) => {
    const user = await api.auth.login(credentials)
    setUser(user)
  }

  const register = async (data: RegisterRequest) => {
    const user = await api.auth.register(data)
    setUser(user)
  }

  const logout = async () => {
    await api.auth.logout()
    setUser(null)
  }

  const value: AuthContextType = {
    user,
    login,
    register,
    logout,
    loading,
    setUser,
  }

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