<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('userToken'); // Исправлено с 'token' на 'userToken'
        const response = await axios.get(
          `/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;
  font-weight: 600;
  position: relative;
  padding-left: 0.75rem;
  display: inline-block;
}

h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
  background: linear-gradient(to bottom, #ff3e68, #ff5252);
  border-radius: 3px;
}

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

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

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

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

.section-title {
  margin-top: 0;
  margin-bottom: 1rem;
  font-weight: 600;
  color: #333;
}

.stats-section {
  border-radius: 8px;
  margin-bottom: 2rem;
}

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

.stat-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  padding: 1.5rem;
  text-align: center;
  transition: all 0.3s ease;
  border-top: 3px solid transparent;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.stat-card.users {
  border-color: #ff3e68;
}

.stat-card.messages {
  border-color: #4caf50;
}

.stat-card.conversations {
  border-color: #2196f3;
}

.stat-card.views {
  border-color: #ff9800;
}

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

.stat-card.users .stat-value {
  color: #ff3e68;
}

.stat-card.messages .stat-value {
  color: #4caf50;
}

.stat-card.conversations .stat-value {
  color: #2196f3;
}

.stat-card.views .stat-value {
  color: #ff9800;
}

.stat-label {
  color: #777;
  font-size: 0.9rem;
}

/* Стили для блока распределения по полу */
.gender-distribution {
  margin-top: 2rem;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 1.5rem;
  border: 1px solid #f1f3f5;
}

.gender-distribution h4 {
  margin: 0 0 1.5rem 0;
  color: #333;
  font-weight: 600;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.gender-distribution h4::before {
  content: '👥';
  font-size: 1.2rem;
}

.gender-chart {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* Горизонтальная диаграмма-полоса */
.gender-bar {
  display: flex;
  height: 40px;
  border-radius: 20px;
  overflow: hidden;
  background-color: #f8f9fa;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.05);
  position: relative;
}

.gender-male,
.gender-female,
.gender-other {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 0.85rem;
  text-shadow: 0 1px 2px rgba(0,0,0,0.3);
  transition: all 0.3s ease;
  min-width: 0;
  position: relative;
}

.gender-male {
  background: linear-gradient(135deg, #2196f3, #1976d2);
}

.gender-female {
  background: linear-gradient(135deg, #e91e63, #c2185b);
}

.gender-other {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
}

.gender-male span,
.gender-female span,
.gender-other span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 8px;
}

/* Анимация при наведении */
.gender-bar:hover .gender-male,
.gender-bar:hover .gender-female,
.gender-bar:hover .gender-other {
  filter: brightness(1.1);
}

/* Легенда */
.gender-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-top: 1rem;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background-color: #f8f9fa;
  border-radius: 8px;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.legend-item:hover {
  background-color: white;
  border-color: #e9ecef;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  transform: translateY(-1px);
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  flex-shrink: 0;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.legend-color.male {
  background: linear-gradient(135deg, #2196f3, #1976d2);
}

.legend-color.female {
  background: linear-gradient(135deg, #e91e63, #c2185b);
}

.legend-color.other {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
}

.legend-label {
  font-size: 0.9rem;
  color: #555;
  font-weight: 500;
  white-space: nowrap;
}

.averages-section {
  margin-top: 1.5rem;
}

.averages-title {
  margin-top: 0;
  margin-bottom: 1rem;
  font-weight: 500;
  color: #333;
  font-size: 1.1rem;
}

.averages-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.average-item {
  background-color: #f8f9fa;
  padding: 0.8rem 1.2rem;
  border-radius: 8px;
  flex: 1;
  min-width: 200px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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

.average-value {
  font-weight: bold;
  color: #ff3e68;
}

.donut-chart {
  max-width: 300px;
  margin: 0 auto;
}

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

.subcard {
  background-color: #f8f9fa;
  padding: 0.8rem;
  border-radius: 6px;
  text-align: center;
}

.subcard-value {
  font-weight: bold;
  color: #ff3e68;
  font-size: 1.2rem;
}

.subcard-label {
  font-size: 0.75rem;
  color: #777;
  margin-top: 0.25rem;
}

/* Адаптивное отображение */
@media (max-width: 767px) {
  .stat-value {
    font-size: 1.8rem;
  }
  
  .gender-bar {
    height: 35px;
  }
  
  .gender-male,
  .gender-female,
  .gender-other {
    font-size: 0.8rem;
  }
  
  .gender-distribution {
    padding: 1rem;
  }
  
  .legend-label {
    font-size: 0.85rem;
  }
  
  h2 {
    font-size: 1.4rem;
    margin-bottom: 1.2rem;
  }
  
  .section-title {
    font-size: 1.1rem;
  }
  
  .stats-cards {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .admin-statistics {
    padding-bottom: calc(56px + env(safe-area-inset-bottom, 0px));
  }
}

@media (max-width: 576px) {
  .stat-card {
    padding: 1.2rem;
  }
  
  .stat-value {
    font-size: 1.6rem;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .gender-distribution {
    padding: 1rem;
    margin-top: 1.5rem;
  }
  
  .gender-bar {
    height: 30px;
  }
  
  .gender-male,
  .gender-female,
  .gender-other {
    font-size: 0.75rem;
  }
  
  .gender-legend {
    flex-direction: column;
    gap: 0.75rem;
    align-items: center;
  }
  
  .legend-item {
    justify-content: center;
    min-width: 120px;
  }
  
  h2 {
    font-size: 1.2rem;
  }
}

/* Устройства с вырезом (notch) */
@supports (padding: env(safe-area-inset-bottom)) {
  .admin-statistics {
    padding-bottom: calc(56px + env(safe-area-inset-bottom, 0px));
  }
}

/* Ландшафтная ориентация на мобильных */
@media (max-height: 450px) and (orientation: landscape) {
  .admin-statistics {
    padding-bottom: calc(50px + env(safe-area-inset-bottom, 0px));
  }
}
</style>