import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/services/api'

export const useGamificationStore = defineStore('gamification', () => {
  // State
  const achievements = ref([])
  const badges = ref([])
  const userStats = ref(null)
  const isLoading = ref(false)
  const error = ref(null)

  // Getters
  const earnedAchievements = computed(() =>
    achievements.value.filter(a => a.is_earned)
  )
  
  const lockedAchievements = computed(() =>
    achievements.value.filter(a => !a.is_earned)
  )
  
  const totalAchievements = computed(() => achievements.value.length)
  
  const earnedCount = computed(() => earnedAchievements.value.length)
  
  const progressPercentage = computed(() => {
    if (totalAchievements.value === 0) return 0
    return Math.round((earnedCount.value / totalAchievements.value) * 100)
  })

  const earnedBadges = computed(() =>
    badges.value.filter(b => b.is_earned)
  )

  // Helper function for API calls (using centralized api instance)
  async function apiFetch(url, options = {}) {
    try {
      const response = await api.get(url, options)
      return response.data
    } catch (error) {
      if (error.response) {
        throw new Error(`API error ${error.response.status}: ${JSON.stringify(error.response.data)}`)
      }
      throw error
    }
  }

  // Actions
  async function fetchAchievements() {
    isLoading.value = true
    error.value = null
    try {
      const data = await apiFetch('/gamification/achievements')
      achievements.value = data.achievements || []
      return data
    } catch (err) {
      console.error('Failed to fetch achievements:', err)
      error.value = err.message
      // No mock fallback - let the error propagate
      achievements.value = []
      throw err
    } finally {
      isLoading.value = false
    }
  }

  async function fetchBadges() {
    isLoading.value = true
    error.value = null
    try {
      const data = await apiFetch('/gamification/my-badges')
      badges.value = data.map(badge => ({
        id: badge.badge_id,
        title: badge.badge_name,
        description: badge.badge_description,
        icon_url: badge.badge_icon_url,
        is_earned: true,
        earned_date: badge.earned_at,
        category: 'badge'
      }))
      return data
    } catch (err) {
      console.error('Failed to fetch badges:', err)
      error.value = err.message
      // No mock fallback - propagate error
      badges.value = []
      throw err
    } finally {
      isLoading.value = false
    }
  }

  async function fetchUserStats() {
    isLoading.value = true
    error.value = null
    try {
      const data = await apiFetch('/gamification/me')
      userStats.value = data
      return data
    } catch (err) {
      console.error('Failed to fetch user stats:', err)
      error.value = err.message
      // No mock fallback - propagate error
      userStats.value = null
      throw err
    } finally {
      isLoading.value = false
    }
  }

  async function fetchAllGamificationData() {
    await Promise.all([
      fetchAchievements(),
      fetchBadges(),
      fetchUserStats()
    ])
  }

  async function earnAchievement(id) {
    // In a real implementation, this would call an API endpoint
    // For now, we'll just update local state
    const achievement = achievements.value.find(a => a.id === id)
    if (achievement && !achievement.is_earned) {
      achievement.is_earned = true
      achievement.earned_date = new Date().toISOString().split('T')[0]
    }
  }

  function resetAchievements() {
    achievements.value.forEach(a => {
      a.is_earned = false
      a.earned_date = null
    })
  }

  // Initialize store with data - RE-ENABLED after token fix
  fetchAllGamificationData()

  return {
    achievements,
    badges,
    userStats,
    earnedAchievements,
    lockedAchievements,
    totalAchievements,
    earnedCount,
    progressPercentage,
    earnedBadges,
    isLoading,
    error,
    fetchAchievements,
    fetchBadges,
    fetchUserStats,
    fetchAllGamificationData,
    earnAchievement,
    resetAchievements
  }
})