<template>
  <div class="admin-reports">
    <div class="header-section">
      <h2>Управление жалобами</h2>
    </div>

    <div class="search-filters">
      <div class="filter-selectors">
        <label :class="{ active: statusFilter === 'all' }">
          <input type="radio" v-model="statusFilter" value="all" @change="loadReports" hidden>
          <span>Все</span>
        </label>
        <label :class="{ active: statusFilter === 'pending' }">
          <input type="radio" v-model="statusFilter" value="pending" @change="loadReports" hidden>
          <span>На рассмотрении</span>
        </label>
        <label :class="{ active: statusFilter === 'resolved' }">
          <input type="radio" v-model="statusFilter" value="resolved" @change="loadReports" hidden>
          <span>Рассмотренные</span>
        </label>
        <label :class="{ active: statusFilter === 'dismissed' }">
          <input type="radio" v-model="statusFilter" value="dismissed" @change="loadReports" hidden>
          <span>Отклоненные</span>
        </label>
      </div>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      <div class="loading-spinner"></div>
      <span>Загрузка жалоб...</span>
    </div>
    
    <div v-if="error" class="error-message">
      <i class="bi-exclamation-triangle"></i>
      {{ error }}
    </div>
    
    <div v-if="!loading && !error" class="reports-container">
      <!-- Десктопное табличное представление -->
      <div class="desktop-table">
        <div class="reports-table-container">
          <table class="reports-table">
            <thead>
              <tr>
                <th class="id-col">ID</th>
                <th class="reason-col">Причина</th>
                <th class="reporter-col">Жалующийся</th>
                <th class="reported-col">На пользователя</th>
                <th class="date-col">Дата подачи</th>
                <th class="status-col">Статус</th>
                <th class="actions-col">Действия</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="report in reports" :key="report._id">
                <td class="id-col">
                  <span class="report-id">{{ shortenId(report._id) }}</span>
                </td>
                <td class="reason-col">
                  <span class="reason-badge" :class="getReasonClass(report.reason)">
                    {{ getReasonText(report.reason) }}
                  </span>
                </td>
                <td class="reporter-col">{{ report.reporter?.name || 'Удален' }}</td>
                <td class="reported-col">{{ report.reportedUser?.name || 'Удален' }}</td>
                <td class="date-col">{{ formatDate(report.createdAt) }}</td>
                <td class="status-col">
                  <span class="status-badge" :class="getStatusClass(report.status)">
                    {{ getStatusText(report.status) }}
                  </span>
                </td>
                <td class="actions-col">
                  <button @click="viewReport(report._id)" class="btn view-btn">
                    <span class="btn-text">Просмотр</span>
                    <i class="bi-eye"></i>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Мобильное карточное представление -->
      <div class="mobile-cards">
        <div v-for="report in reports" :key="report._id" class="report-card" @click="viewReport(report._id)">
          <div class="card-header">
            <div class="card-id">
              <i class="bi-file-text"></i>
              <span>{{ shortenId(report._id) }}</span>
            </div>
            <span class="status-badge" :class="getStatusClass(report.status)">
              {{ getStatusText(report.status) }}
            </span>
          </div>
          
          <div class="card-content">
            <div class="reason-info">
              <span class="reason-badge" :class="getReasonClass(report.reason)">
                {{ getReasonText(report.reason) }}
              </span>
            </div>
            
            <div class="users-info">
              <div class="user-item">
                <i class="bi-person-exclamation"></i>
                <span>{{ report.reporter?.name || 'Удален' }}</span>
              </div>
              <div class="arrow">→</div>
              <div class="user-item">
                <i class="bi-person-x"></i>
                <span>{{ report.reportedUser?.name || 'Удален' }}</span>
              </div>
            </div>
            
            <div class="card-footer">
              <span class="date">{{ formatDate(report.createdAt) }}</span>
              <i class="bi-chevron-right"></i>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="reports.length === 0" class="no-results">
        <i class="bi-inbox"></i>
        <h3>Жалобы не найдены</h3>
        <p>Нет жалоб, соответствующих выбранным фильтрам</p>
      </div>
      
      <div v-if="pagination.pages > 1" class="pagination">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          <i class="bi-chevron-left"></i>
          <span class="btn-text-lg">Назад</span>
        </button>
        
        <div class="pagination-info">
          <span class="page-text">Страница {{ currentPage }} из {{ pagination.pages }}</span>
          <span class="total-text">({{ pagination.total }} жалоб)</span>
        </div>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage === pagination.pages"
          class="pagination-btn"
        >
          <span class="btn-text-lg">Далее</span>
          <i class="bi-chevron-right"></i>
        </button>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'AdminReports',
  setup() {
    const router = useRouter();
    const reports = ref([]);
    const loading = ref(false);
    const error = ref(null);
    const statusFilter = ref('all');
    const currentPage = ref(1);
    const pagination = ref({
      page: 1,
      pages: 1,
      total: 0,
      limit: 20
    });

    // Загрузка списка жалоб
    const loadReports = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const params = {
          page: currentPage.value,
          limit: pagination.value.limit
        };
        
        if (statusFilter.value !== 'all') {
          params.status = statusFilter.value;
        }
        
        const token = localStorage.getItem('userToken');
        const response = await axios.get(`/api/admin/reports`, {
          params,
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        
        reports.value = response.data.reports;
        pagination.value = response.data.pagination;
      } catch (err) {
        console.error('Ошибка при загрузке жалоб:', err);
        error.value = 'Ошибка при загрузке списка жалоб. Пожалуйста, попробуйте позже.';
      } finally {
        loading.value = false;
      }
    };

    // Функция для сокращения ID
    const shortenId = (id) => {
      return id ? id.substring(0, 6) + '...' : '';
    };

    // Форматирование даты
    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'
      });
    };

    // Получение текста причины жалобы
    const getReasonText = (reason) => {
      const reasons = {
        inappropriate_content: 'Неподходящий контент',
        fake_profile: 'Фальшивый профиль',
        harassment: 'Домогательства',
        spam: 'Спам',
        offensive_behavior: 'Оскорбительное поведение',
        underage: 'Несовершеннолетний',
        other: 'Другое'
      };
      return reasons[reason] || reason;
    };

    // Получение CSS класса для причины
    const getReasonClass = (reason) => {
      const classes = {
        inappropriate_content: 'reason-inappropriate',
        fake_profile: 'reason-fake',
        harassment: 'reason-harassment',
        spam: 'reason-spam',
        offensive_behavior: 'reason-offensive',
        underage: 'reason-underage',
        other: 'reason-other'
      };
      return classes[reason] || 'reason-other';
    };

    // Получение текста статуса
    const getStatusText = (status) => {
      const statuses = {
        pending: 'На рассмотрении',
        resolved: 'Рассмотрена',
        dismissed: 'Отклонена'
      };
      return statuses[status] || status;
    };

    // Получение CSS класса для статуса
    const getStatusClass = (status) => {
      const classes = {
        pending: 'status-pending',
        resolved: 'status-resolved',
        dismissed: 'status-dismissed'
      };
      return classes[status] || 'status-pending';
    };

    // Переход на детальную страницу жалобы
    const viewReport = (reportId) => {
      router.push({ name: 'AdminReportDetail', params: { id: reportId } });
    };

    // Изменение страницы пагинации
    const changePage = (page) => {
      if (page < 1 || page > pagination.value.pages) return;
      
      currentPage.value = page;
      loadReports();
    };

    onMounted(() => {
      loadReports();
    });

    return {
      reports,
      loading,
      error,
      statusFilter,
      currentPage,
      pagination,
      loadReports,
      shortenId,
      formatDate,
      getReasonText,
      getReasonClass,
      getStatusText,
      getStatusClass,
      viewReport,
      changePage
    };
  }
}
</script>

<style scoped>
.admin-reports {
  padding-bottom: 2rem;
  max-width: 100%;
}

h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
  font-weight: 600;
  position: relative;
  padding-left: 0.5rem;
  display: inline-block;
  font-size: 1.75rem; /* Добавлено свойство размера шрифта */
}

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

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

.search-filters {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.filter-selectors {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.filter-selectors label {
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.9rem;
  background-color: #f5f5f5;
  color: #555;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e0e0e0;
  white-space: nowrap;
  text-align: center;
}

.filter-selectors label:hover {
  background-color: #eaeaea;
}

.filter-selectors label.active {
  background-color: #ff3e68;
  color: white;
  border-color: #ff3e68;
  font-weight: 500;
}

.loading-indicator {
  text-align: center;
  padding: 2rem;
  color: #666;
  font-style: italic;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.loading-spinner {
  width: 1.5rem;
  height: 1.5rem;
  border: 3px solid rgba(255, 255, 255, 0.6);
  border-top: 3px solid #007bff;
  border-radius: 50%;
  animation: spin 0.75s linear infinite;
}

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

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 0.75rem 1rem;
  border-radius: 0.375rem;
  border: 1px solid #f5c6cb;
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.reports-container {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.desktop-table {
  display: block;
}

.reports-table-container {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.reports-table {
  width: 100%;
  border-collapse: collapse;
}

.reports-table th,
.reports-table td {
  padding: 0.85rem;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

.reports-table th {
  background: linear-gradient(to right, #f8f9fa, #e9ecef);
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #dee2e6;
}

.reports-table tbody tr:hover {
  background-color: rgba(255, 62, 104, 0.02);
}

.reason-badge,
.status-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 1rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.reason-inappropriate { background-color: #f8d7da; color: #721c24; }
.reason-fake { background-color: #fff3cd; color: #856404; }
.reason-harassment { background-color: #d1ecf1; color: #0c5460; }
.reason-spam { background-color: #d4edda; color: #155724; }
.reason-offensive { background-color: #f8d7da; color: #721c24; }
.reason-underage { background-color: #f8d7da; color: #721c24; }
.reason-other { background-color: #e2e3e5; color: #383d41; }

.status-pending { background-color: #fff3cd; color: #856404; }
.status-resolved { background-color: #d4edda; color: #155724; }
.status-dismissed { background-color: #e2e3e5; color: #383d41; }

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

.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  padding: 0.4rem 0.75rem;
  border: none;
  border-radius: 0.375rem;
  cursor: pointer;
  text-decoration: none;
  font-size: 0.85rem;
  font-weight: 500;
  transition: all 0.2s ease;
  min-width: 36px;
  min-height: 36px;
  justify-content: center;
}

.view-btn {
  background-color: #007bff;
  color: white;
}

.view-btn:hover {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.reports-table .id-col,
.reports-table .reason-col,
.reports-table .reporter-col,
.reports-table .reported-col,
.reports-table .date-col,
.reports-table .status-col,
.reports-table .actions-col {
  white-space: nowrap;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  background-color: #f8f9fa;
  border-top: 1px solid #dee2e6;
}

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

.pagination-btn:hover:not(:disabled) {
  background-color: #f8f9fa;
  border-color: #ced4da;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-info {
  color: #6c757d;
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.page-text {
  font-weight: 600;
  font-size: 0.95rem;
}

.total-text {
  font-size: 0.8rem;
  color: #6c757d;
}

/* Мобильные карточки */
.mobile-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.report-card {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.report-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border-color: #007bff;
}

.report-card:active {
  transform: translateY(0);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e9ecef;
  background: linear-gradient(to right, #f8f9fa, #ffffff);
}

.card-id {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 600;
  color: #333;
  font-size: 0.9rem;
}

.card-id i {
  font-size: 1.1rem;
  color: #007bff;
}

.card-content {
  padding: 1rem;
}

.reason-info {
  margin-bottom: 0.75rem;
}

.reason-info .reason-badge {
  font-size: 0.8rem;
  padding: 0.3rem 0.6rem;
}

.users-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 0.5rem;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.85rem;
  color: #555;
  flex: 1;
  min-width: 0;
}

.user-item span {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.user-item i {
  flex-shrink: 0;
  font-size: 1rem;
}

.arrow {
  font-size: 1.2rem;
  color: #007bff;
  font-weight: bold;
  flex-shrink: 0;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.8rem;
  color: #777;
  padding-top: 0.5rem;
  border-top: 1px solid #f0f0f0;
}

.card-footer .date {
  font-weight: 500;
}

.card-footer i {
  font-size: 1.1rem;
  color: #007bff;
  transition: transform 0.2s ease;
}

.report-card:hover .card-footer i {
  transform: translateX(2px);
}

.no-results {
  text-align: center;
  padding: 4rem 2rem;
  color: #6c757d;
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.no-results i {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #dee2e6;
}

.no-results h3 {
  margin: 0 0 0.5rem 0;
  color: #495057;
  font-size: 1.25rem;
}

.no-results p {
  margin: 0;
  font-size: 0.95rem;
}

/* Улучшенная пагинация */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid #e9ecef;
}

.pagination-btn {
  padding: 0.6rem 1rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  min-height: 40px;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.pagination-btn:disabled {
  background-color: #6c757d;
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.pagination-info {
  color: #495057;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.2rem;
  text-align: center;
}

/* Адаптивные стили для разных экранов */

/* Очень маленькие экраны (до 480px) */
@media (max-width: 480px) {
  .admin-reports {
    padding: 1rem 0.5rem calc(60px + env(safe-area-inset-bottom, 0px)) 0.5rem;
  }
  
  .header-section {
    flex-direction: column;
    align-items: stretch;
    gap: 1rem;
  }
  
  .search-filters {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .filter-selectors {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    width: 100%;
    gap: 0.5rem;
  }
  
  .filter-selectors label {
    min-width: 0;
    width: 100%;
    font-size: 0.8rem;
    padding: 0.4rem 0.5rem;
  }
  
  .card-header {
    padding: 0.75rem;
  }
  
  .card-content {
    padding: 0.75rem;
  }
  
  .users-info {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .user-item {
    justify-content: center;
    padding: 0.25rem;
  }
  
  .arrow {
    transform: rotate(90deg);
  }
  
  .pagination {
    padding: 0.75rem;
    flex-direction: column;
    gap: 1rem;
  }
  
  .pagination-btn {
    width: 100%;
    justify-content: center;
  }
  
  .btn-text-lg {
    display: none;
  }
  
  h2 {
    font-size: 1.1rem;
  }
}

/* Маленькие экраны (481px - 767px) */
@media (min-width: 481px) and (max-width: 767px) {
  .admin-reports {
    padding: 1rem calc(60px + env(safe-area-inset-bottom, 0px)) 1rem;
  }
  
  .filter-selectors {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
  }
  
  .filter-selectors label {
    padding: 0.4rem 0.8rem;
    background: #f8f9fa;
    border-radius: 1rem;
    border: 1px solid #dee2e6;
    transition: all 0.2s ease;
  }
  
  .filter-selectors label.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
  }
  
  .filter-selectors input[type="radio"] {
    display: none;
  }
  
  .users-info {
    align-items: center;
  }
  
  .pagination {
    flex-direction: row;
  }
}

/* Средние экраны (768px - 991px) */
@media (min-width: 768px) and (max-width: 991px) {
  .admin-reports {
    padding: 1.5rem 1rem calc(60px + env(safe-area-inset-bottom, 0px)) 1rem;
  }
  
  .mobile-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 1.5rem;
  }
  
  .header-section {
    flex-direction: row;
  }
}

/* Большие экраны (992px - 1199px) */
@media (min-width: 992px) and (max-width: 1199px) {
  .admin-reports {
    padding: 2rem 1.5rem;
  }
  
  .mobile-cards {
    display: none;
  }
  
  .desktop-table {
    display: block;
  }
  
  .reports-table th,
  .reports-table td {
    padding: 0.75rem 0.5rem;
    font-size: 0.9rem;
  }
  
  .id-col { width: 8%; }
  .reason-col { width: 20%; }
  .reporter-col { width: 18%; }
  .reported-col { width: 18%; }
  .date-col { width: 15%; }
  .status-col { width: 12%; }
  .actions-col { width: 9%; }
}

/* Очень большие экраны (1200px+) */
@media (min-width: 1200px) {
  .admin-reports {
    padding: 2rem;
  }
  
  .mobile-cards {
    display: none;
  }
  
  .desktop-table {
    display: block;
  }
  
  .reports-table th,
  .reports-table td {
    padding: 1rem;
  }
  
  .id-col { width: 10%; }
  .reason-col { width: 20%; }
  .reporter-col { width: 17%; }
  .reported-col { width: 17%; }
  .date-col { width: 16%; }
  .status-col { width: 12%; }
  .actions-col { width: 8%; }
}

/* Скрываем таблицу на мобильных, показываем карточки */
@media (max-width: 991px) {
  .desktop-table {
    display: none;
  }
  
  .mobile-cards {
    display: grid;
  }
}

/* Планшеты в ландшафтной ориентации */
@media (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {
  .desktop-table {
    display: block;
  }
  
  .mobile-cards {
    display: none;
  }
  
  .reports-table th,
  .reports-table td {
    padding: 0.6rem 0.4rem;
    font-size: 0.85rem;
  }
}

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

/* Высокие экраны */
@media (min-height: 800px) {
  .admin-reports {
    min-height: calc(100vh - 200px);
  }
}

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