// stores/stats.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient, withLoading } from './helpers/api'

export const useStatsStore = defineStore('stats', () => {
  // State
  const detailedStats = ref(null)
  const workoutHistory = ref([])
  const monthlyStats = ref([])
  const yearlyStats = ref([])
  const paceAnalysis = ref(null)
  const progressTrends = ref([])
  const loading = ref(false)
  const error = ref('')

  // Getters
  const totalWorkouts = computed(() => workoutHistory.value.length)
  
  const totalDistance = computed(() => 
    detailedStats.value?.total_distance || 
    workoutHistory.value.reduce((sum, workout) => sum + (workout.distance_km || 0), 0)
  )

  const totalTime = computed(() =>
    detailedStats.value?.total_time_min ||
    workoutHistory.value.reduce((sum, workout) => sum + (workout.duration_min || 0), 0)
  )

  const averagePace = computed(() => {
    if (totalDistance.value === 0 || totalTime.value === 0) return '0:00'
    
    const totalMinutes = totalTime.value
    const avgPaceMinPerKm = totalMinutes / totalDistance.value
    const minutes = Math.floor(avgPaceMinPerKm)
    const seconds = Math.round((avgPaceMinPerKm - minutes) * 60)
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  })

  const weeklyStats = computed(() => {
    const last7Days = workoutHistory.value
      .filter(workout => {
        const workoutDate = new Date(workout.date)
        const weekAgo = new Date()
        weekAgo.setDate(weekAgo.getDate() - 7)
        return workoutDate >= weekAgo
      })
    
    return {
      workouts: last7Days.length,
      distance: last7Days.reduce((sum, w) => sum + (w.distance_km || 0), 0),
      time: last7Days.reduce((sum, w) => sum + (w.duration_min || 0), 0)
    }
  })

  // Actions
  const fetchDetailedStats = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/stats/detailed')
        detailedStats.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Detailed stats endpoint not available, using fallback', error)
        // Fallback на базовую статистику
        return { success: true, data: detailedStats.value }
      }
    })
  }

  const fetchWorkoutHistory = async (params = {}) => {
    return withLoading({ loading, error }, async () => {
      try {
        const queryString = new URLSearchParams(params).toString()
        const response = await apiClient.get(`/user/workouts?${queryString}`)
        workoutHistory.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Workout history endpoint not available, using mock data', error)
        // Mock данные для демонстрации
        workoutHistory.value = generateMockWorkoutHistory()
        return { success: true, data: workoutHistory.value }
      }
    })
  }

  const fetchMonthlyStats = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/stats/monthly')
        monthlyStats.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Monthly stats endpoint not available, generating from history', error)
        monthlyStats.value = generateMonthlyStatsFromHistory()
        return { success: true, data: monthlyStats.value }
      }
    })
  }

  const fetchYearlyStats = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/stats/yearly')
        yearlyStats.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Yearly stats endpoint not available, generating from history', error)
        yearlyStats.value = generateYearlyStatsFromHistory()
        return { success: true, data: yearlyStats.value }
      }
    })
  }

  const fetchPaceAnalysis = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/stats/pace-analysis')
        paceAnalysis.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Pace analysis endpoint not available, generating from history', error)
        paceAnalysis.value = generatePaceAnalysis()
        return { success: true, data: paceAnalysis.value }
      }
    })
  }

  const fetchProgressTrends = async (period = '6months') => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get(`/user/stats/progress-trends?period=${period}`)
        progressTrends.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Progress trends endpoint not available, generating mock data', error)
        progressTrends.value = generateProgressTrends(period)
        return { success: true, data: progressTrends.value }
      }
    })
  }

  const exportStats = async (format = 'csv') => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get(`/user/stats/export?format=${format}`, {
          responseType: 'blob'
        })
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  // Вспомогательные функции для mock данных
  const generateMockWorkoutHistory = () => {
    const types = ['easy', 'tempo', 'interval', 'long', 'recovery']
    const history = []
    
    for (let i = 0; i < 30; i++) {
      const date = new Date()
      date.setDate(date.getDate() - i * 2)
      
      const type = types[Math.floor(Math.random() * types.length)]
      const distance = type === 'long' ? 
        (8 + Math.random() * 12) : 
        (3 + Math.random() * 7)
      
      const pace = type === 'interval' ? '4:30' : 
                  type === 'tempo' ? '5:00' : '5:30'
      
      history.push({
        id: i + 1,
        type,
        distance_km: parseFloat(distance.toFixed(1)),
        duration_min: Math.round(distance * (pace === '4:30' ? 4.5 : pace === '5:00' ? 5 : 5.5) * 60),
        pace,
        calories: Math.round(distance * 60),
        date: date.toISOString().split('T')[0],
        notes: i % 5 === 0 ? 'Хорошая тренировка' : ''
      })
    }
    
    return history
  }

  const generateMonthlyStatsFromHistory = () => {
    const months = []
    for (let i = 0; i < 6; i++) {
      const date = new Date()
      date.setMonth(date.getMonth() - i)
      months.push({
        month: date.toLocaleDateString('ru-RU', { month: 'long', year: 'numeric' }),
        distance_km: parseFloat((25 + Math.random() * 50).toFixed(1)),
        workouts: Math.floor(8 + Math.random() * 12),
        total_time_min: Math.floor(1500 + Math.random() * 3000)
      })
    }
    return months.reverse()
  }

  const generateYearlyStatsFromHistory = () => {
    const years = []
    const currentYear = new Date().getFullYear()
    
    for (let i = 0; i < 3; i++) {
      years.push({
        year: currentYear - i,
        distance_km: parseFloat((300 + Math.random() * 500).toFixed(1)),
        workouts: Math.floor(100 + Math.random() * 150),
        total_time_min: Math.floor(18000 + Math.random() * 20000)
      })
    }
    return years.reverse()
  }

  const generatePaceAnalysis = () => {
    return {
      easy: '5:45',
      tempo: '5:15',
      interval: '4:45',
      long: '5:30',
      recovery: '6:00',
      overall_trend: 'improving',
      best_pace: '4:30',
      best_pace_date: '2024-03-15'
    }
  }

  const generateProgressTrends = (period) => {
    const trends = []
    const points = period === '6months' ? 6 : 12
    
    for (let i = 0; i < points; i++) {
      trends.push({
        period: `Период ${i + 1}`,
        distance: parseFloat((20 + Math.random() * 30).toFixed(1)),
        pace: parseFloat((5.0 + Math.random() * 1.0).toFixed(2)),
        workouts: Math.floor(8 + Math.random() * 8)
      })
    }
    return trends
  }

  const resetStatsStore = () => {
    detailedStats.value = null
    workoutHistory.value = []
    monthlyStats.value = []
    yearlyStats.value = []
    paceAnalysis.value = null
    progressTrends.value = []
    loading.value = false
    error.value = ''
  }

  return {
    // State
    detailedStats,
    workoutHistory,
    monthlyStats,
    yearlyStats,
    paceAnalysis,
    progressTrends,
    loading,
    error,

    // Getters
    totalWorkouts,
    totalDistance,
    totalTime,
    averagePace,
    weeklyStats,

    // Actions
    fetchDetailedStats,
    fetchWorkoutHistory,
    fetchMonthlyStats,
    fetchYearlyStats,
    fetchPaceAnalysis,
    fetchProgressTrends,
    exportStats,
    resetStatsStore
  }
})