<template>
  <div class="admin-statistics">
    <h2>Статистика приложения</h2>
    
    <div v-if="loading" class="loading-indicator">
      <div class="loading-spinner"></div>
      <div>Загрузка статистики...</div>
    </div>
    
    <div v-if="error" class="error-message">
      <i class="bi-exclamation-triangle"></i>
      {{ 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 users">
            <div class="stat-value">{{ statistics.users.total }}</div>
            <div class="stat-label">Всего пользователей</div>
          </div>
          
          <div class="stat-card active">
            <div class="stat-value">{{ statistics.users.active }}</div>
            <div class="stat-label">Активных</div>
          </div>
          
          <div class="stat-card blocked">
            <div class="stat-value">{{ statistics.users.inactive }}</div>
            <div class="stat-label">Заблокированных</div>
          </div>
          
          <div class="stat-card new">
            <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 messages">
            <div class="stat-value">{{ statistics.activity.totalMessages }}</div>
            <div class="stat-label">Всего сообщений</div>
          </div>
          
          <div class="stat-card conversations">
            <div class="stat-value">{{ statistics.activity.totalConversations }}</div>
            <div class="stat-label">Всего диалогов</div>
          </div>
          
          <div class="stat-card views">
            <div class="stat-value">{{ statistics.activity.totalProfileViews }}</div>
            <div class="stat-label">Просмотров профилей</div>
          </div>
        </div>
        
        <div class="average-stats-container">
          <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>
  </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: 1.5rem;
  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;
}

h3 {
  margin-top: 0;
  margin-bottom: 1.25rem;
  color: #333;
  font-weight: 600;
  font-size: 1.3rem;
}

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

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 2rem;
  color: #666;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 62, 104, 0.2);
  border-left: 4px solid #ff3e68;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  padding: 1rem;
  background-color: #ffebee;
  border-left: 4px solid #f44336;
  color: #d32f2f;
  margin-bottom: 1.5rem;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.error-message i {
  color: #d32f2f;
  font-size: 1.2rem;
}

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

.stat-section {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 1.5rem;
  border: 1px solid #f1f3f5;
}

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

.stat-card {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 1.5rem;
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid #f1f3f5;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(to right, transparent, #ff3e68, transparent);
}

.stat-card.users::before {
  background: linear-gradient(to right, #ff3e68, #ff5252);
}

.stat-card.active::before {
  background: linear-gradient(to right, #4caf50, #8bc34a);
}

.stat-card.blocked::before {
  background: linear-gradient(to right, #f44336, #e91e63);
}

.stat-card.new::before {
  background: linear-gradient(to right, #ff9800, #ffc107);
}

.stat-card.messages::before {
  background: linear-gradient(to right, #2196f3, #03a9f4);
}

.stat-card.conversations::before {
  background: linear-gradient(to right, #9c27b0, #673ab7);
}

.stat-card.views::before {
  background: linear-gradient(to right, #009688, #4caf50);
}

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

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

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

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

.stat-card.blocked .stat-value {
  color: #f44336;
}

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

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

.stat-card.conversations .stat-value {
  color: #9c27b0;
}

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

.stat-label {
  color: #777;
  font-size: 0.95rem;
  font-weight: 500;
}

/* Стили для блока распределения по полу */
.gender-distribution {
  margin-top: 2rem;
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 1.5rem;
  border: 1px solid #f1f3f5;
}

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

/* Горизонтальная диаграмма-полоса */
.gender-bar {
  display: flex;
  height: 40px;
  border-radius: 20px;
  overflow: hidden;
  background-color: #f1f3f5;
  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.9rem;
  text-shadow: 0 1px 2px rgba(0,0,0,0.2);
  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: 0.75rem;
  margin-top: 1rem;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background-color: white;
  border-radius: 8px;
  transition: all 0.2s ease;
  border: 1px solid #f1f3f5;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.legend-item:hover {
  background-color: white;
  border-color: #e9ecef;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  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;
}

/* Блок средних значений */
.average-stats-container {
  margin-top: 1.5rem;
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 1.5rem;
  border: 1px solid #f1f3f5;
}

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

.average-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 1rem 1.25rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  border: 1px solid #f1f3f5;
  transition: all 0.2s ease;
}

.average-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 6px rgba(0,0,0,0.08);
}

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

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

/* Адаптивное отображение */
@media (max-width: 1199px) {
  .admin-statistics {
    padding: 1.25rem;
  }
  
  .stat-cards {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  }
}

@media (max-width: 991px) {
  .admin-statistics {
    padding: 1rem;
    /* Добавляем отступ для нижней навигации */
    padding-bottom: calc(1rem + 56px + env(safe-area-inset-bottom, 0px));
  }
  
  .stat-card {
    padding: 1.25rem;
  }
  
  .stat-cards {
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  }
  
  .stat-value {
    font-size: 2rem;
  }
  
  .gender-distribution, 
  .average-stats-container {
    padding: 1.25rem;
  }
  
  .average-stats {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 767px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 0.8rem;
  }
  
  .stat-value {
    font-size: 1.8rem;
  }
  
  .stat-label {
    font-size: 0.85rem;
  }
  
  .stat-section {
    padding: 1.25rem;
  }
  
  .gender-bar {
    height: 35px;
  }
  
  .gender-male,
  .gender-female,
  .gender-other {
    font-size: 0.8rem;
  }
  
  .gender-distribution,
  .average-stats-container {
    padding: 1.25rem;
    margin-top: 1.5rem;
  }
  
  .legend-item {
    padding: 0.4rem 0.6rem;
    flex: 1;
    justify-content: center;
  }
  
  h2 {
    font-size: 1.3rem;
    margin-bottom: 1.2rem;
  }
  
  h3 {
    font-size: 1.2rem;
    margin-bottom: 1rem;
  }
  
  h4 {
    font-size: 1rem;
    margin: 0.75rem 0;
  }
  
  .average-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
  }
  
  .admin-statistics {
    padding-bottom: calc(56px + env(safe-area-inset-bottom, 0px));
  }
}

@media (max-width: 576px) {
  .stat-card {
    padding: 1rem;
  }
  
  .stat-value {
    font-size: 1.5rem;
    margin-bottom: 0.25rem;
  }
  
  .stat-label {
    font-size: 0.8rem;
  }
  
  .admin-statistics {
    padding: 0.75rem;
    padding-bottom: calc(0.75rem + 56px + env(safe-area-inset-bottom, 0px));
  }
  
  .stat-section {
    padding: 1rem;
  }
  
  .gender-distribution,
  .average-stats-container {
    padding: 1rem;
    margin-top: 1rem;
  }
  
  .gender-bar {
    height: 30px;
  }
  
  .gender-male,
  .gender-female,
  .gender-other {
    font-size: 0.75rem;
  }
  
  .gender-legend {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .legend-item {
    width: 100%;
  }
  
  h2 {
    font-size: 1.2rem;
    margin-bottom: 1rem;
  }
  
  h3 {
    font-size: 1.1rem;
    margin-bottom: 0.8rem;
  }
  
  h4 {
    font-size: 0.95rem;
    margin: 0.5rem 0;
  }
}

@media (max-width: 480px) {
  .stat-cards {
    gap: 0.6rem;
  }
  
  .stat-card {
    border-radius: 8px;
    padding: 0.8rem;
  }
  
  .stat-value {
    font-size: 1.3rem;
    margin-bottom: 0.2rem;
  }
  
  .stat-label {
    font-size: 0.75rem;
  }
  
  .average-label {
    font-size: 0.85rem;
  }
  
  .average-value {
    font-size: 1rem;
  }
}

@media (max-width: 360px) {
  .admin-statistics {
    padding: 0.5rem;
    padding-bottom: calc(0.5rem + 56px + env(safe-area-inset-bottom, 0px));
  }
  
  .stat-section,
  .gender-distribution,
  .average-stats-container {
    padding: 0.75rem;
    border-radius: 8px;
  }
  
  .gender-bar {
    height: 25px;
  }
}

/* Устройства с вырезом (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));
  }
  
  .stat-cards {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .stat-card {
    padding: 0.75rem;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
  
  .stat-label {
    font-size: 0.75rem;
  }
  
  .gender-distribution {
    margin-top: 1rem;
  }
  
  .gender-legend {
    flex-direction: row;
  }
}
</style>