import { createContext, useContext, useMemo, useState } from 'react'
import { clearToken, clearUser, getToken, getUser } from '../utils/storage'
import api from '../services/api'

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [token, setTokenState] = useState(() => getToken())
  const [user, setUserState] = useState(() => getUser())
  const [loading, setLoading] = useState(false)

  const isAuthenticated = !!token

  const login = async ({ username, password }) => {
    setLoading(true)
    try {
      const res = await api.post('/api/auth/login', { username, password })
      const nextToken = res.data.token
      const nextUser = { _id: res.data._id, username: res.data.username }

      setTokenState(nextToken)
      setUserState(nextUser)

      return nextUser
    } finally {
      setLoading(false)
    }
  }

  const register = async ({ username, password }) => {
    setLoading(true)
    try {
      const res = await api.post('/api/auth/register', { username, password })
      const nextToken = res.data.token
      const nextUser = { _id: res.data._id, username: res.data.username }

      setTokenState(nextToken)
      setUserState(nextUser)

      return nextUser
    } finally {
      setLoading(false)
    }
  }

  const logout = async () => {
    clearToken()
    clearUser()
    setTokenState(null)
    setUserState(null)
  }

  const value = useMemo(
    () => ({
      user,
      token,
      loading,
      isAuthenticated,
      login,
      register,
      logout,
    }),
    [user, token, loading, isAuthenticated],
  )

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

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


