const API_BASE = 'http://localhost:8082'

export interface LoginRequest {
  username: string
  password: string
}

export interface RegisterRequest {
  username: string
  password: string
  email?: string
}

export interface LoginResponse {
  token: string
  user: any
}

export const useAuth = () => {
  const token = localStorage.getItem('token')
  const user = localStorage.getItem('user')

  const login = async (data: LoginRequest): Promise<LoginResponse> => {
    const response = await fetch(`${API_BASE}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Login failed')
    }

    const result = await response.json()

    // Save token and user info
    localStorage.setItem('token', result.token)
    localStorage.setItem('user', JSON.stringify(result.user))

    return result
  }

  const register = async (data: RegisterRequest): Promise<any> => {
    const response = await fetch(`${API_BASE}/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Registration failed')
    }

    return await response.json()
  }

  const logout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  const getToken = () => {
    return localStorage.getItem('token')
  }

  const getUser = () => {
    const userStr = localStorage.getItem('user')
    return userStr ? JSON.parse(userStr) : null
  }

  const isLoggedIn = () => {
    return !!token
  }

  const getCurrentUser = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('Not authenticated')
    }

    const response = await fetch(`${API_BASE}/auth/me`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Failed to get user')
    }

    const user = await response.json()
    localStorage.setItem('user', JSON.stringify(user))
    return user
  }

  return {
    login,
    register,
    logout,
    getToken,
    getUser,
    isLoggedIn,
    getCurrentUser,
  }
}
