<template>
  <div class="admin-user-detail">
    <div class="header-controls">
      <button @click="goBack" class="back-btn">
        &laquo; Назад к списку пользователей
      </button>
      
      <button 
        v-if="user" 
        @click="toggleUserStatus" 
        class="status-btn"
        :class="user.isActive ? 'block-btn' : 'unblock-btn'"
      >
        {{ user.isActive ? 'Заблокировать' : 'Разблокировать' }}
      </button>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      Загрузка информации о пользователе...
    </div>
    
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-if="user && !loading" class="user-container">
      <h2>Информация о пользователе</h2>
      
      <div class="user-profile">
        <div class="user-header">
          <div class="user-photo" v-if="userProfilePhoto">
            <img :src="userProfilePhoto" alt="Фото профиля">
          </div>
          <div class="user-photo placeholder" v-else>
            <div class="initials">{{ getUserInitials() }}</div>
          </div>
          
          <div class="user-name-status">
            <h3>{{ user.name }}</h3>
            <span class="status-badge" :class="{ 'active': user.isActive, 'blocked': !user.isActive }">
              {{ user.isActive ? 'Активен' : 'Заблокирован' }}
            </span>
          </div>
        </div>
        
        <div class="user-details">
          <div class="detail-group">
            <div class="detail-item">
              <div class="detail-label">ID</div>
              <div class="detail-value">{{ user._id }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Email</div>
              <div class="detail-value">{{ user.email }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Пол</div>
              <div class="detail-value">{{ getGenderText(user.gender) }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Дата рождения</div>
              <div class="detail-value">{{ formatDate(user.dateOfBirth) }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Возраст</div>
              <div class="detail-value">{{ calculateAge(user.dateOfBirth) }} лет</div>
            </div>
          </div>
          
          <div class="detail-group">
            <div class="detail-item">
              <div class="detail-label">Город</div>
              <div class="detail-value">{{ user.location?.city || 'Не указан' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Страна</div>
              <div class="detail-value">{{ user.location?.country || 'Не указана' }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Дата регистрации</div>
              <div class="detail-value">{{ formatDate(user.createdAt) }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">Последнее посещение</div>
              <div class="detail-value">{{ formatDate(user.lastSeen) }}</div>
            </div>
          </div>
        </div>
        
        <div class="user-bio" v-if="user.bio">
          <h4>О себе</h4>
          <p>{{ user.bio }}</p>
        </div>
      </div>
      
      <div class="user-stats">
        <h3>Статистика активности</h3>
        
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value">{{ user.stats?.messagesCount || 0 }}</div>
            <div class="stat-label">Сообщений</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ user.stats?.conversationsCount || 0 }}</div>
            <div class="stat-label">Диалогов</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ user.stats?.profileViewsCount || 0 }}</div>
            <div class="stat-label">Просмотров профиля</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ user.stats?.matchesCount || 0 }}</div>
            <div class="stat-label">Взаимных симпатий</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ user.stats?.likesGivenCount || 0 }}</div>
            <div class="stat-label">Выражений симпатии</div>
          </div>
        </div>
      </div>
      
      <div class="user-photos" v-if="user.photos && user.photos.length > 0">
        <h3>Фотографии пользователя</h3>
        
        <div class="photos-grid">
          <div 
            v-for="(photo, index) in user.photos" 
            :key="index" 
            class="photo-item"
          >
            <img :src="photo.url" alt="Фото пользователя">
            <div v-if="photo.isProfilePhoto" class="photo-badge">Основное фото</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import toastService from '@/services/toastService';

export default {
  name: 'AdminUserDetail',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const router = useRouter();
    const route = useRoute();
    const user = ref(null);
    const loading = ref(false);
    const error = ref(null);
    
    // Получить основное фото пользователя
    const userProfilePhoto = computed(() => {
      if (!user.value || !user.value.photos) return null;
      
      const profilePhoto = user.value.photos.find(p => p.isProfilePhoto);
      return profilePhoto ? profilePhoto.url : (user.value.photos.length > 0 ? user.value.photos[0].url : null);
    });
    
    const loadUserDetails = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const token = localStorage.getItem('userToken'); // Исправлено с 'token' на 'userToken'
        const response = await axios.get(
          `/api/admin/users/${props.id}`,
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        );
        
        user.value = response.data;
      } catch (err) {
        console.error('Ошибка при загрузке данных пользователя:', err);
        error.value = 'Ошибка при загрузке информации о пользователе. Пожалуйста, попробуйте позже.';
      } finally {
        loading.value = false;
      }
    };
    
    // Переход назад к списку пользователей
    const goBack = () => {
      router.push({ name: 'AdminUsers' });
    };
    
    // Изменение статуса пользователя (блокировка/разблокировка)
    const toggleUserStatus = async () => {
      try {
        loading.value = true;
        
        const token = localStorage.getItem('userToken'); // Исправлено с 'token' на 'userToken'
        const response = await axios.put(
          `/api/admin/users/${props.id}/toggle-active`,
          {},
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        );
        
        // Обновляем статус пользователя
        user.value.isActive = response.data.isActive;
        
        // Заменяем alert на уведомление через сервис
        const actionType = user.value.isActive ? 'success' : 'warning';
        toastService.add(response.data.message, actionType, 3000);
      } catch (err) {
        console.error('Ошибка при изменении статуса пользователя:', err);
        toastService.error('Ошибка при изменении статуса пользователя');
      } finally {
        loading.value = false;
      }
    };
    
    // Получение инициалов пользователя для отображения, если нет фото
    const getUserInitials = () => {
      if (!user.value || !user.value.name) return '?';
      
      return user.value.name
        .split(' ')
        .map(n => n[0])
        .join('')
        .toUpperCase()
        .substring(0, 2);
    };
    
    // Форматирование пола
    const getGenderText = (gender) => {
      switch(gender) {
        case 'male': return 'Мужской';
        case 'female': return 'Женский';
        case 'other': return 'Другой';
        default: return 'Не указан';
      }
    };
    
    // Расчет возраста
    const calculateAge = (dateOfBirthString) => {
      if (!dateOfBirthString) return 'Не указан';
      
      const dob = new Date(dateOfBirthString);
      const today = new Date();
      let age = today.getFullYear() - dob.getFullYear();
      const monthDiff = today.getMonth() - dob.getMonth();
      
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())) {
        age--;
      }
      
      return age;
    };
    
    // Форматирование даты
    const formatDate = (dateString) => {
      if (!dateString) return 'Не указана';
      
      const date = new Date(dateString);
      return date.toLocaleString('ru-RU', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    onMounted(() => {
      loadUserDetails();
    });
    
    return {
      user,
      loading,
      error,
      userProfilePhoto,
      goBack,
      toggleUserStatus,
      getUserInitials,
      getGenderText,
      calculateAge,
      formatDate
    };
  }
}
</script>

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

.header-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.back-btn {
  padding: 0.5rem 1rem;
  background-color: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: pointer;
  color: #495057;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.back-btn:hover {
  background-color: #f8f9fa;
  transform: translateX(-2px);
}

.status-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.status-btn:hover {
  transform: translateY(-2px);
}

.block-btn {
  background-color: rgba(211, 47, 47, 0.1);
  color: #d32f2f;
}

.block-btn:hover {
  background-color: rgba(211, 47, 47, 0.15);
}

.unblock-btn {
  background-color: rgba(46, 125, 50, 0.1);
  color: #2e7d32;
}

.unblock-btn:hover {
  background-color: rgba(46, 125, 50, 0.15);
}

.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;
}

h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
  position: relative;
  padding-left: 0.75rem;
  display: inline-block;
  font-weight: 600;
}

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: 1rem;
  color: #333;
  font-weight: 600;
}

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

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

.user-header {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.user-photo {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 3px solid white;
}

.user-photo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-photo.placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ff3e68;
  color: white;
  font-size: 2rem;
  font-weight: bold;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
  color: #ff3e68;
}

.user-name-status {
  flex: 1;
  max-width: calc(100% - 120px); /* Учитываем размер фото и отступ */
}

.user-name-status h3 {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
  color: #ff3e68;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 50px;
  font-size: 0.8rem;
  font-weight: 500;
  white-space: nowrap;
}

.user-status {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 50px;
  font-size: 0.8rem;
  font-weight: 500;
}

.user-status.active {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.user-status.blocked {
  background-color: #ffebee;
  color: #d32f2f;
}

.user-details {
  margin-top: 1.5rem;
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.detail-group {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 0.875rem;
  color: #6c757d;
  margin-bottom: 0.25rem;
}

.detail-value {
  font-weight: 500;
  color: #495057;
}

.user-bio {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e9ecef;
}

.user-bio h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #333;
  font-weight: 600;
}

.user-bio p {
  margin: 0;
  line-height: 1.5;
  color: #495057;
  white-space: pre-wrap;
}

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

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

.stat-card {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.stat-card:hover {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  border-color: rgba(255, 62, 104, 0.1);
  transform: translateY(-2px);
}

.stat-value {
  font-size: 1.75rem;
  font-weight: bold;
  color: #ff3e68;
  margin-bottom: 0.5rem;
  line-height: 1;
}

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

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

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

.photo-item {
  border-radius: 8px;
  overflow: hidden;
  aspect-ratio: 3/4;
  max-height: 300px;
}

.photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.photo-item:hover img {
  transform: scale(1.03);
}

.no-photos {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
  background-color: #f8f9fa;
  border-radius: 6px;
}

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

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

.badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 50px;
  font-size: 0.8rem;
  font-weight: 500;
  text-align: center;
}

.badge-primary {
  background-color: rgba(25, 118, 210, 0.1);
  color: #1976d2;
}

/* Адаптивные стили */
@media (max-width: 767px) {
  .header-controls {
    flex-direction: column;
    gap: 1rem;
  }
  
  .back-btn, .status-btn {
    width: 100%;
    justify-content: center;
  }
  
  .user-header {
    flex-direction: column;
    text-align: center;
  }
  
  .user-photo {
    margin: 0 auto;
  }
  
  .user-name {
    font-size: 1.3rem;
  }
  
  .details-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
  
  .admin-user-detail {
    padding-bottom: calc(56px + env(safe-area-inset-bottom, 0px));
  }
}

@media (max-width: 576px) {
  .photos-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

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

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