import { useState, useEffect } from 'react'
import { authApi, TokenResponse } from '../api/auth'

interface AuthState {
  isAuthenticated: boolean
  username: string | null
  isLoading: boolean
}

export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>({
    isAuthenticated: false,
    username: null,
    isLoading: true,
  })

  useEffect(() => {
    const token = localStorage.getItem('access_token')
    if (token) {
      // Verify token by fetching user info
      authApi
        .me()
        .then((user) => {
          setAuthState({
            isAuthenticated: true,
            username: user.username,
            isLoading: false,
          })
        })
        .catch(() => {
          localStorage.removeItem('access_token')
          localStorage.removeItem('refresh_token')
          setAuthState({
            isAuthenticated: false,
            username: null,
            isLoading: false,
          })
        })
    } else {
      setAuthState({
        isAuthenticated: false,
        username: null,
        isLoading: false,
      })
    }
  }, [])

  const login = async (username: string, password: string) => {
    try {
      const tokens: TokenResponse = await authApi.login({ username, password })
      localStorage.setItem('access_token', tokens.access_token)
      localStorage.setItem('refresh_token', tokens.refresh_token)
      const user = await authApi.me()
      setAuthState({
        isAuthenticated: true,
        username: user.username,
        isLoading: false,
      })
      return { success: true }
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.detail || 'Login failed',
      }
    }
  }

  const logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    setAuthState({
      isAuthenticated: false,
      username: null,
      isLoading: false,
    })
  }

  return {
    ...authState,
    login,
    logout,
  }
}

