<template>
  <div class="page detailed-stats">
    <div class="page-header">
      <button class="btn btn-back" @click="$router.go(-1)">← Назад</button>
      <h1>📊 Подробная статистика</h1>
    </div>

    <div v-if="loading" class="loading">Загрузка статистики...</div>

    <div v-else class="stats-content">
      <!-- Общая сводка -->
      <div class="stats-summary">
        <h2>Общая сводка</h2>
        <div class="summary-grid">
          <div class="summary-card">
            <h3>🏃 Всего пробег</h3>
            <p class="value">{{ totalDistance }} км</p>
          </div>
          <div class="summary-card">
            <h3>⏱️ Общее время</h3>
            <p class="value">{{ formatTime(totalTime) }}</p>
          </div>
          <div class="summary-card">
            <h3>📅 Тренировок</h3>
            <p class="value">{{ totalWorkouts }}</p>
          </div>
          <div class="summary-card">
            <h3>⚡ Средний темп</h3>
            <p class="value">{{ averagePace }}/км</p>
          </div>
        </div>
      </div>

      <!-- Статистика за неделю -->
      <div class="stats-section">
        <h2>📅 Статистика за неделю</h2>
        <div class="weekly-stats">
          <div class="stat-item">
            <span class="label">Пробег:</span>
            <span class="value">{{ weeklyStats.distance }} км</span>
          </div>
          <div class="stat-item">
            <span class="label">Тренировки:</span>
            <span class="value">{{ weeklyStats.workouts }}</span>
          </div>
          <div class="stat-item">
            <span class="label">Время:</span>
            <span class="value">{{ formatTime(weeklyStats.time) }}</span>
          </div>
        </div>
      </div>

      <!-- История тренировок -->
      <div class="stats-section">
        <div class="section-header">
          <h2>📈 История тренировок</h2>
          <div class="filters">
            <select v-model="workoutFilter" @change="applyWorkoutFilters">
              <option value="all">Все типы</option>
              <option value="easy">Легкие</option>
              <option value="tempo">Темповые</option>
              <option value="interval">Интервалы</option>
              <option value="long">Длинные</option>
            </select>
            <select v-model="timeFilter" @change="applyWorkoutFilters">
              <option value="30">30 дней</option>
              <option value="90">90 дней</option>
              <option value="365">Год</option>
              <option value="all">Все время</option>
            </select>
          </div>
        </div>
        
        <div class="workout-history">
          <div v-for="workout in workoutHistory" :key="workout.id" class="workout-card">
            <div class="workout-header">
              <span class="workout-type" :class="workout.type">{{ getWorkoutTypeLabel(workout.type) }}</span>
              <span class="workout-date">{{ formatDate(workout.date) }}</span>
            </div>
            <div class="workout-details">
              <div class="detail">
                <span class="label">Дистанция:</span>
                <span class="value">{{ workout.distance_km }} км</span>
              </div>
              <div class="detail">
                <span class="label">Время:</span>
                <span class="value">{{ formatTime(workout.duration_min) }}</span>
              </div>
              <div class="detail">
                <span class="label">Темп:</span>
                <span class="value">{{ workout.pace }}/км</span>
              </div>
              <div v-if="workout.calories" class="detail">
                <span class="label">Калории:</span>
                <span class="value">{{ workout.calories }}</span>
              </div>
            </div>
            <div v-if="workout.notes" class="workout-notes">
              {{ workout.notes }}
            </div>
          </div>
        </div>
      </div>

      <!-- Ежемесячная статистика -->
      <div class="stats-section">
        <h2>📊 Ежемесячная статистика</h2>
        <div class="monthly-stats">
          <div v-for="month in monthlyStats" :key="month.month" class="month-stat">
            <h4>{{ month.month }}</h4>
            <div class="stat-details">
              <span>{{ month.distance_km }} км</span>
              <span>{{ month.workouts }} тренировок</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Анализ темпа -->
      <div v-if="paceAnalysis" class="stats-section">
        <h2>⚡ Анализ темпа</h2>
        <div class="pace-analysis">
          <div class="pace-item">
            <span>Легкие:</span>
            <strong>{{ paceAnalysis.easy }}/км</strong>
          </div>
          <div class="pace-item">
            <span>Темповые:</span>
            <strong>{{ paceAnalysis.tempo }}/км</strong>
          </div>
          <div class="pace-item">
            <span>Интервалы:</span>
            <strong>{{ paceAnalysis.interval }}/км</strong>
          </div>
          <div class="pace-item">
            <span>Длинные:</span>
            <strong>{{ paceAnalysis.long }}/км</strong>
          </div>
        </div>
      </div>

      <!-- Кнопки действий -->
      <div class="action-buttons">
        <button class="btn btn-outline" @click="refreshStats">
          🔄 Обновить статистику
        </button>
        <button class="btn btn-secondary" @click="exportStats">
          📥 Экспорт данных
        </button>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
      <button class="btn-retry" @click="loadStatsData">Попробовать снова</button>
    </div>
  </div>
</template>

<script>
import { useStatsStore } from '../stores/stats'
import { ref, onMounted, computed } from 'vue'

export default {
  name: 'DetailedStats',
  setup() {
    const statsStore = useStatsStore()
    
    // Фильтры
    const workoutFilter = ref('all')
    const timeFilter = ref('30')
    
    // Загрузка данных
    const loadStatsData = async () => {
      await Promise.all([
        statsStore.fetchDetailedStats(),
        statsStore.fetchWorkoutHistory(),
        statsStore.fetchMonthlyStats(),
        statsStore.fetchPaceAnalysis()
      ])
    }
    
    // Применение фильтров
    const applyWorkoutFilters = () => {
      const params = {}
      if (workoutFilter.value !== 'all') {
        params.type = workoutFilter.value
      }
      if (timeFilter.value !== 'all') {
        params.days = timeFilter.value
      }
      statsStore.fetchWorkoutHistory(params)
    }
    
    // Экспорт данных
    const exportStats = async () => {
      const result = await statsStore.exportStats('csv')
      if (result.success) {
        // Создаем временную ссылку для скачивания
        const url = window.URL.createObjectURL(result.data)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `running_stats_${new Date().toISOString().split('T')[0]}.csv`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(url)
      }
    }
    
    // Обновление статистики
    const refreshStats = async () => {
      await loadStatsData()
    }
    
    // Форматирование времени
    const formatTime = (minutes) => {
      if (!minutes) return '0 мин'
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return hours > 0 ? `${hours}ч ${mins}мин` : `${mins} мин`
    }
    
    // Форматирование даты
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('ru-RU')
    }
    
    // Метки типов тренировок
    const getWorkoutTypeLabel = (type) => {
      const labels = {
        'easy': 'Легкая',
        'tempo': 'Темповая',
        'interval': 'Интервалы',
        'long': 'Длинная',
        'recovery': 'Восстановительная'
      }
      return labels[type] || type
    }
    
    onMounted(() => {
      loadStatsData()
    })
    
    return {
      loading: computed(() => statsStore.loading),
      error: computed(() => statsStore.error),
      totalDistance: computed(() => statsStore.totalDistance),
      totalTime: computed(() => statsStore.totalTime),
      totalWorkouts: computed(() => statsStore.totalWorkouts),
      averagePace: computed(() => statsStore.averagePace),
      weeklyStats: computed(() => statsStore.weeklyStats),
      workoutHistory: computed(() => statsStore.workoutHistory),
      monthlyStats: computed(() => statsStore.monthlyStats),
      paceAnalysis: computed(() => statsStore.paceAnalysis),
      workoutFilter,
      timeFilter,
      applyWorkoutFilters,
      exportStats,
      refreshStats,
      formatTime,
      formatDate,
      getWorkoutTypeLabel,
      loadStatsData
    }
  }
}
</script>

<style scoped>
.detailed-stats {
  max-width: 1000px;
  margin: 0 auto;
  padding: 1rem;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
}

.btn-back {
  background: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
}

.btn-back:hover {
  background: #545b62;
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.stats-summary {
  background: white;
  padding: 1.5rem;
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.summary-card {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  padding: 1.5rem;
  border-radius: 12px;
  text-align: center;
  border: 2px solid #e9ecef;
}

.summary-card h3 {
  margin: 0 0 0.5rem;
  color: #555;
  font-size: 0.9rem;
}

.summary-card .value {
  margin: 0;
  font-size: 1.5rem;
  font-weight: bold;
  color: #2e8b57;
}

.stats-section {
  background: white;
  padding: 1.5rem;
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.filters {
  display: flex;
  gap: 0.5rem;
}

.filters select {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: white;
}

.weekly-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #2e8b57;
}

.workout-history {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 400px;
  overflow-y: auto;
}

.workout-card {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 10px;
  border-left: 4px solid #2e8b57;
}

.workout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.workout-type {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
  color: white;
}

.workout-type.easy { background: #28a745; }
.workout-type.tempo { background: #ffc107; color: #000; }
.workout-type.interval { background: #dc3545; }
.workout-type.long { background: #007bff; }
.workout-type.recovery { background: #6c757d; }

.workout-date {
  color: #666;
  font-size: 0.9rem;
}

.workout-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.detail {
  display: flex;
  justify-content: space-between;
}

.detail .label {
  color: #666;
}

.detail .value {
  font-weight: 500;
}

.workout-notes {
  padding-top: 0.5rem;
  border-top: 1px solid #e9ecef;
  color: #555;
  font-style: italic;
}

.monthly-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.month-stat {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  text-align: center;
}

.month-stat h4 {
  margin: 0 0 0.5rem;
  color: #333;
}

.stat-details {
  display: flex;
  justify-content: space-around;
  color: #666;
}

.pace-analysis {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
}

.pace-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn-retry {
  background: #2e8b57;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  margin-left: 1rem;
}

.btn-retry:hover {
  background: #26734d;
}

/* Адаптивность */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .filters {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .summary-grid {
    grid-template-columns: 1fr 1fr;
  }
}
</style>