import { API_ENDPOINTS } from '@/config/api-config'
import { api } from '@/services/api'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import router from '@/router'

interface AuthState {
  accessToken: string | null
  refreshToken: string | null
  user: {
    email: string
    name: string
    id?: string | number
  } | null
}

export const useAuthStore = defineStore('auth', () => {
  // State
  const accessToken = ref<string | null>(localStorage.getItem('token'))
  const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))
  const user = ref<AuthState['user']>(null)

  // Getters
  const isAuthenticated = computed(() => !!accessToken.value)
  const getUser = computed(() => user.value)

  // Actions
  const setTokens = (tokens: { access_token: string; refresh_token?: string }) => {
    try {
      accessToken.value = tokens.access_token
      localStorage.setItem('token', tokens.access_token)
      if (tokens.refresh_token) {
        refreshToken.value = tokens.refresh_token
        localStorage.setItem('refreshToken', tokens.refresh_token)
      }
    } catch (error) {
      console.error('Error setting tokens:', error)
      clearTokens()
    }
  }

  const clearTokens = () => {
    try {
      accessToken.value = null
      refreshToken.value = null
      user.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    } catch (error) {
      console.error('Error clearing tokens:', error)
    }
  }

  const setUser = (userData: AuthState['user']) => {
    user.value = userData
  }

  const fetchCurrentUser = async () => {
    if (!accessToken.value) {
      console.log('No access token found, clearing tokens')
      clearTokens()
      return null
    }
    try {
      console.log('Fetching current user profile...')
      const response = await api.get(API_ENDPOINTS.USERS.PROFILE)
      console.log('User profile fetched:', response.data)
      setUser(response.data)
      return response.data
    } catch (error: any) {
      console.error('AuthStore: Failed to fetch current user:', error)
      clearTokens()
      return null
    }
  }

  const login = async (email: string, password: string) => {
    console.log('Attempting login...')
    const formData = new FormData()
    formData.append('username', email)
    formData.append('password', password)

    const response = await api.post(API_ENDPOINTS.AUTH.LOGIN, formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })

    console.log('Login successful, setting tokens...')
    const { access_token, refresh_token } = response.data
    setTokens({ access_token, refresh_token })
    // Fetch profile data after login
    await fetchCurrentUser()
    return response.data
  }

  const signup = async (userData: { name: string; email: string; password: string }) => {
    const response = await api.post(API_ENDPOINTS.AUTH.SIGNUP, userData)
    return response.data
  }

  const logout = async () => {
    clearTokens()
    await router.push('/auth/login')
  }

  return {
    accessToken,
    user,
    refreshToken,
    isAuthenticated,
    getUser,
    setTokens,
    clearTokens,
    setUser,
    fetchCurrentUser,
    login,
    signup,
    logout,
  }
})
