<template>
  <div class="admin-statistics">
    <h2>Статистика приложения</h2>
    
    <div v-if="loading" class="loading-indicator">
      Загрузка статистики...
    </div>
    
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-if="statistics && !loading" class="statistics-container">
      <div class="stat-section users-section">
        <h3>Пользователи</h3>
        
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">{{ statistics.users.total }}</div>
            <div class="stat-label">Всего пользователей</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{{ statistics.users.active }}</div>
            <div class="stat-label">Активных пользователей</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{{ statistics.users.inactive }}</div>
            <div class="stat-label">Заблокированных</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{{ statistics.users.newIn30Days }}</div>
            <div class="stat-label">Новых за 30 дней</div>
          </div>
        </div>
        
        <div class="gender-distribution">
          <h4>Распределение по полу</h4>
          <div class="gender-chart">
            <div class="gender-bar">
              <div 
                class="gender-male" 
                :style="{ 
                  width: calculateGenderPercentage('male') + '%' 
                }"
              >
                <span v-if="calculateGenderPercentage('male') > 10">
                  {{ statistics.users.genderDistribution.male }}
                </span>
              </div>
              <div 
                class="gender-female" 
                :style="{ 
                  width: calculateGenderPercentage('female') + '%' 
                }"
              >
                <span v-if="calculateGenderPercentage('female') > 10">
                  {{ statistics.users.genderDistribution.female }}
                </span>
              </div>
              <div 
                class="gender-other" 
                :style="{ 
                  width: calculateGenderPercentage('other') + '%' 
                }"
              >
                <span v-if="calculateGenderPercentage('other') > 10">
                  {{ statistics.users.genderDistribution.other }}
                </span>
              </div>
            </div>
            <div class="gender-legend">
              <div class="legend-item">
                <div class="legend-color male"></div>
                <div class="legend-label">Мужчины ({{ calculateGenderPercentage('male') }}%)</div>
              </div>
              <div class="legend-item">
                <div class="legend-color female"></div>
                <div class="legend-label">Женщины ({{ calculateGenderPercentage('female') }}%)</div>
              </div>
              <div class="legend-item">
                <div class="legend-color other"></div>
                <div class="legend-label">Другое ({{ calculateGenderPercentage('other') }}%)</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="stat-section activity-section">
        <h3>Активность пользователей</h3>
        
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">{{ statistics.activity.totalMessages }}</div>
            <div class="stat-label">Всего сообщений</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{{ statistics.activity.totalConversations }}</div>
            <div class="stat-label">Всего диалогов</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-value">{{ statistics.activity.totalProfileViews }}</div>
            <div class="stat-label">Просмотров профилей</div>
          </div>
        </div>
        
        <h4>Средняя активность</h4>
        <div class="average-stats">
          <div class="average-item">
            <div class="average-label">Сообщений на пользователя:</div>
            <div class="average-value">{{ statistics.activity.averages.messagesPerUser }}</div>
          </div>
          <div class="average-item">
            <div class="average-label">Диалогов на пользователя:</div>
            <div class="average-value">{{ statistics.activity.averages.conversationsPerUser }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'AdminStatistics',
  setup() {
    const statistics = ref(null);
    const loading = ref(false);
    const error = ref(null);
    
    const loadStatistics = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get(
          `${import.meta.env.VITE_API_URL}/api/admin/statistics`,
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        );
        
        statistics.value = response.data;
      } catch (err) {
        console.error('Ошибка при загрузке статистики:', err);
        error.value = 'Ошибка при загрузке статистики. Пожалуйста, попробуйте позже.';
      } finally {
        loading.value = false;
      }
    };
    
    // Расчет процентов распределения пола
    const calculateGenderPercentage = (gender) => {
      if (!statistics.value) return 0;
      
      const { male, female, other } = statistics.value.users.genderDistribution;
      const total = male + female + other;
      
      if (total === 0) return 0;
      
      const genderCount = statistics.value.users.genderDistribution[gender];
      return Math.round((genderCount / total) * 100);
    };
    
    onMounted(() => {
      loadStatistics();
    });
    
    return {
      statistics,
      loading,
      error,
      calculateGenderPercentage
    };
  }
}
</script>

<style scoped>
.admin-statistics {
  padding-bottom: 2rem;
}

h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
}

h3 {
  margin-top: 0;
  margin-bottom: 1.25rem;
  color: #333;
}

h4 {
  margin-top: 1.5rem;
  margin-bottom: 1rem;
  color: #444;
}

.loading-indicator {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message {
  padding: 1rem;
  background-color: #ffebee;
  color: #d32f2f;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.statistics-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.stat-section {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  padding: 1.5rem;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

.stat-card {
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 1.25rem;
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #ff3e68;
  margin-bottom: 0.5rem;
}

.stat-label {
  color: #666;
}

.gender-distribution {
  margin-top: 1.5rem;
}

.gender-chart {
  margin-top: 1rem;
}

.gender-bar {
  display: flex;
  height: 40px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 1rem;
}

.gender-bar > div {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 500;
  transition: width 0.5s ease;
}

.gender-male {
  background-color: #2196f3;
}

.gender-female {
  background-color: #e91e63;
}

.gender-other {
  background-color: #9c27b0;
}

.gender-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 1.25rem;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.legend-color.male {
  background-color: #2196f3;
}

.legend-color.female {
  background-color: #e91e63;
}

.legend-color.other {
  background-color: #9c27b0;
}

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

.average-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9f9;
  padding: 1rem;
  border-radius: 6px;
}

.average-label {
  font-weight: 400;
  color: #555;
}

.average-value {
  font-weight: 600;
  color: #ff3e68;
}
</style>