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

export const usePersonalBestsStore = defineStore('personalBests', () => {
  // State
  const personalBests = ref([])
  const bestsSummary = ref(null)
  const loading = ref(false)
  const error = ref('')

  // Getters
  const verifiedBests = computed(() => 
    personalBests.value.filter(best => best.verified)
  )

  const pendingBests = computed(() =>
    personalBests.value.filter(best => !best.verified)
  )

  const bestsByDistance = computed(() => {
    const grouped = {}
    personalBests.value.forEach(best => {
      if (!grouped[best.distance_type]) {
        grouped[best.distance_type] = []
      }
      grouped[best.distance_type].push(best)
    })
    return grouped
  })

  const currentBests = computed(() => {
    const bests = {}
    personalBests.value.forEach(best => {
      if (!bests[best.distance_type] || 
          new Date(best.date) > new Date(bests[best.distance_type].date)) {
        bests[best.distance_type] = best
      }
    })
    return bests
  })

  const distanceLabels = {
    '5k': '5 км',
    '10k': '10 км',
    'half_marathon': 'Полумарафон (21.1 км)',
    'marathon': 'Марафон (42.2 км)',
    'other': 'Другая дистанция'
  }

  // Actions
  const fetchPersonalBests = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/personal-bests')
        personalBests.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Personal bests endpoint not available, using mock data', error)
        personalBests.value = generateMockPersonalBests()
        return { success: true, data: personalBests.value }
      }
    })
  }

  const fetchBestsSummary = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/user/personal-bests/summary')
        bestsSummary.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Personal bests summary endpoint not available', error)
        bestsSummary.value = generateBestsSummary()
        return { success: true, data: bestsSummary.value }
      }
    })
  }

  const createPersonalBest = async (bestData) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.post('/user/personal-bests', bestData)
        personalBests.value.push(response.data)
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const updatePersonalBest = async (id, updateData) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.put(`/user/personal-bests/${id}`, updateData)
        const index = personalBests.value.findIndex(best => best.id === id)
        if (index !== -1) {
          personalBests.value[index] = response.data
        }
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const deletePersonalBest = async (id) => {
    return withLoading({ loading, error }, async () => {
      try {
        await apiClient.delete(`/user/personal-bests/${id}`)
        personalBests.value = personalBests.value.filter(best => best.id !== id)
        return { success: true }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const verifyPersonalBest = async (id) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.patch(`/user/personal-bests/${id}/verify`)
        const index = personalBests.value.findIndex(best => best.id === id)
        if (index !== -1) {
          personalBests.value[index] = response.data
        }
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const calculatePace = (distance, time) => {
    // time в формате "HH:MM:SS" или "MM:SS"
    const timeParts = time.split(':').map(part => parseInt(part))
    let totalSeconds = 0
    
    if (timeParts.length === 2) {
      // MM:SS
      totalSeconds = timeParts[0] * 60 + timeParts[1]
    } else if (timeParts.length === 3) {
      // HH:MM:SS
      totalSeconds = timeParts[0] * 3600 + timeParts[1] * 60 + timeParts[2]
    }
    
    const paceSecondsPerKm = totalSeconds / distance
    const paceMinutes = Math.floor(paceSecondsPerKm / 60)
    const paceSeconds = Math.round(paceSecondsPerKm % 60)
    
    return `${paceMinutes}:${paceSeconds.toString().padStart(2, '0')}`
  }

  // Вспомогательные функции для mock данных
  const generateMockPersonalBests = () => {
    return [
      {
        id: 1,
        distance_type: '5k',
        time: '23:45',
        pace: '4:45',
        date: '2024-03-15',
        verified: true,
        event_name: 'Весенний забег',
        location: 'Городской парк'
      },
      {
        id: 2,
        distance_type: '10k',
        time: '48:15',
        pace: '4:49',
        date: '2024-02-20',
        verified: true,
        event_name: 'Зимний марафон',
        location: 'Центральный стадион'
      },
      {
        id: 3,
        distance_type: 'half_marathon',
        time: '1:48:30',
        pace: '5:08',
        date: '2024-01-10',
        verified: true,
        event_name: 'Новогодний полумарафон',
        location: 'Набережная'
      },
      {
        id: 4,
        distance_type: '5k',
        time: '22:30',
        pace: '4:30',
        date: '2024-03-20',
        verified: false,
        event_name: 'Тренировочный забег',
        location: 'Лесопарк'
      }
    ]
  }

  const generateBestsSummary = () => {
    return {
      best_5k: '23:45',
      best_5k_pace: '4:45',
      best_10k: '48:15',
      best_10k_pace: '4:49',
      best_half_marathon: '1:48:30',
      best_half_marathon_pace: '5:08',
      best_marathon: null,
      best_marathon_pace: null
    }
  }

  const resetPersonalBestsStore = () => {
    personalBests.value = []
    bestsSummary.value = null
    loading.value = false
    error.value = ''
  }

  return {
    // State
    personalBests,
    bestsSummary,
    loading,
    error,

    // Getters
    verifiedBests,
    pendingBests,
    bestsByDistance,
    currentBests,
    distanceLabels,

    // Actions
    fetchPersonalBests,
    fetchBestsSummary,
    createPersonalBest,
    updatePersonalBest,
    deletePersonalBest,
    verifyPersonalBest,
    calculatePace,
    resetPersonalBestsStore
  }
})