<template>
  <div class="admin-blocked-devices">
    <div class="page-header">
      <h1>Заблокированные устройства</h1>
      <div class="stats">
        <div class="stat-card">
          <div class="stat-number">{{ blockedDevices.length }}</div>
          <div class="stat-label">Всего заблокировано</div>
        </div>
      </div>
    </div>

    <div class="search-filters">
      <div class="search-bar">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Поиск по device ID, причине или дате..."
          @input="filterDevices"
        >
      </div>
      <div class="filters">
        <select v-model="statusFilter" @change="filterDevices">
          <option value="">Все статусы</option>
          <option value="active">Активные</option>
          <option value="expired">Истекшие</option>
        </select>
        <select v-model="reasonFilter" @change="filterDevices">
          <option value="">Все причины</option>
          <option value="multiple_violations">Множественные нарушения</option>
          <option value="spam">Спам</option>
          <option value="harassment">Домогательства</option>
          <option value="fake_profile">Фейковый профиль</option>
          <option value="other">Другое</option>
        </select>
      </div>
    </div>

    <div class="devices-table" v-if="filteredDevices.length > 0">
      <table>
        <thead>
          <tr>
            <th>Device ID</th>
            <th>Причина</th>
            <th>Заблокировано</th>
            <th>Истекает</th>
            <th>Статус</th>
            <th>Действия</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="device in paginatedDevices" :key="device._id">
            <td>
              <div class="device-id">
                <code>{{ device.deviceId.substring(0, 16) }}...</code>
                <button 
                  @click="copyToClipboard(device.deviceId)"
                  class="copy-btn"
                  title="Копировать полный ID"
                >
                  📋
                </button>
              </div>
            </td>
            <td>
              <span class="reason-badge" :class="device.reason">
                {{ getReasonText(device.reason) }}
              </span>
            </td>
            <td>{{ formatDate(device.blockedAt) }}</td>
            <td>
              <span v-if="device.expiresAt" :class="{ 'expired': isExpired(device.expiresAt) }">
                {{ formatDate(device.expiresAt) }}
              </span>
              <span v-else class="permanent">Навсегда</span>
            </td>
            <td>
              <span class="status-badge" :class="getDeviceStatus(device)">
                {{ getDeviceStatusText(device) }}
              </span>
            </td>
            <td>
              <div class="actions">
                <button 
                  @click="viewDeviceDetails(device)"
                  class="btn btn-sm btn-outline"
                >
                  Детали
                </button>
                <button 
                  @click="unblockDevice(device._id)"
                  class="btn btn-sm btn-danger"
                  :disabled="isExpired(device.expiresAt)"
                >
                  Разблокировать
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Пагинация -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          @click="currentPage--"
          :disabled="currentPage === 1"
          class="btn btn-outline"
        >
          Назад
        </button>
        <span class="page-info">
          Страница {{ currentPage }} из {{ totalPages }}
        </span>
        <button 
          @click="currentPage++"
          :disabled="currentPage === totalPages"
          class="btn btn-outline"
        >
          Далее
        </button>
      </div>
    </div>

    <div v-else class="no-data">
      <div class="no-data-icon">🚫</div>
      <h3>Заблокированных устройств не найдено</h3>
      <p>{{ searchQuery ? 'Попробуйте изменить параметры поиска' : 'Пока нет заблокированных устройств' }}</p>
    </div>

    <!-- Модальное окно с деталями устройства -->
    <div v-if="selectedDevice" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>Детали заблокированного устройства</h3>
          <button @click="closeModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="device-details">
            <div class="detail-row">
              <label>Device ID:</label>
              <code>{{ selectedDevice.deviceId }}</code>
            </div>
            <div class="detail-row">
              <label>Причина блокировки:</label>
              <span class="reason-badge" :class="selectedDevice.reason">
                {{ getReasonText(selectedDevice.reason) }}
              </span>
            </div>
            <div class="detail-row" v-if="selectedDevice.description">
              <label>Описание:</label>
              <p>{{ selectedDevice.description }}</p>
            </div>
            <div class="detail-row">
              <label>Дата блокировки:</label>
              <span>{{ formatDate(selectedDevice.blockedAt) }}</span>
            </div>
            <div class="detail-row" v-if="selectedDevice.expiresAt">
              <label>Дата истечения:</label>
              <span :class="{ 'expired': isExpired(selectedDevice.expiresAt) }">
                {{ formatDate(selectedDevice.expiresAt) }}
              </span>
            </div>
            <div class="detail-row">
              <label>Статус:</label>
              <span class="status-badge" :class="getDeviceStatus(selectedDevice)">
                {{ getDeviceStatusText(selectedDevice) }}
              </span>
            </div>
            <div class="detail-row" v-if="selectedDevice.blockedBy">
              <label>Заблокировал:</label>
              <span>{{ selectedDevice.blockedBy.username || selectedDevice.blockedBy.email }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeModal" class="btn btn-outline">Закрыть</button>
          <button 
            @click="unblockDevice(selectedDevice._id)"
            class="btn btn-danger"
            :disabled="isExpired(selectedDevice.expiresAt)"
          >
            Разблокировать
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/services/api'

export default {
  name: 'AdminBlockedDevices',
  data() {
    return {
      blockedDevices: [],
      filteredDevices: [],
      searchQuery: '',
      statusFilter: '',
      reasonFilter: '',
      currentPage: 1,
      itemsPerPage: 20,
      selectedDevice: null,
      loading: false
    }
  },
  computed: {
    paginatedDevices() {
      const start = (this.currentPage - 1) * this.itemsPerPage
      const end = start + this.itemsPerPage
      return this.filteredDevices.slice(start, end)
    },
    totalPages() {
      return Math.ceil(this.filteredDevices.length / this.itemsPerPage)
    }
  },
  async mounted() {
    await this.loadBlockedDevices()
  },
  methods: {
    async loadBlockedDevices() {
      try {
        this.loading = true
        const response = await api.getBlockedDevices()
        this.blockedDevices = response.data.devices || []
        this.filteredDevices = [...this.blockedDevices]
      } catch (error) {
        console.error('Ошибка загрузки заблокированных устройств:', error)
        this.$toast.error('Ошибка загрузки данных')
      } finally {
        this.loading = false
      }
    },
    filterDevices() {
      let filtered = [...this.blockedDevices]

      // Поиск по тексту
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        filtered = filtered.filter(device => 
          device.deviceId.toLowerCase().includes(query) ||
          this.getReasonText(device.reason).toLowerCase().includes(query) ||
          (device.description && device.description.toLowerCase().includes(query))
        )
      }

      // Фильтр по статусу
      if (this.statusFilter) {
        filtered = filtered.filter(device => {
          const status = this.getDeviceStatus(device)
          return status === this.statusFilter
        })
      }

      // Фильтр по причине
      if (this.reasonFilter) {
        filtered = filtered.filter(device => device.reason === this.reasonFilter)
      }

      this.filteredDevices = filtered
      this.currentPage = 1
    },
    getDeviceStatus(device) {
      if (device.expiresAt && this.isExpired(device.expiresAt)) {
        return 'expired'
      }
      return 'active'
    },
    getDeviceStatusText(device) {
      const status = this.getDeviceStatus(device)
      return {
        active: 'Активная',
        expired: 'Истекшая'
      }[status]
    },
    getReasonText(reason) {
      const reasons = {
        multiple_violations: 'Множественные нарушения',
        spam: 'Спам',
        harassment: 'Домогательства',
        fake_profile: 'Фейковый профиль',
        other: 'Другое'
      }
      return reasons[reason] || reason
    },
    isExpired(expiresAt) {
      if (!expiresAt) return false
      return new Date(expiresAt) < new Date()
    },
    formatDate(dateString) {
      return new Date(dateString).toLocaleString('ru-RU')
    },
    viewDeviceDetails(device) {
      this.selectedDevice = device
    },
    closeModal() {
      this.selectedDevice = null
    },
    async unblockDevice(deviceId) {
      if (!confirm('Вы уверены, что хотите разблокировать это устройство?')) {
        return
      }

      try {
        await api.unblockDevice(deviceId)
        this.$toast.success('Устройство разблокировано')
        await this.loadBlockedDevices()
        this.closeModal()
      } catch (error) {
        console.error('Ошибка разблокировки устройства:', error)
        this.$toast.error('Ошибка разблокировки устройства')
      }
    },
    async copyToClipboard(text) {
      try {
        await navigator.clipboard.writeText(text)
        this.$toast.success('ID скопирован в буфер обмена')
      } catch (error) {
        console.error('Ошибка копирования в буфер обмена:', error)
        this.$toast.error('Ошибка копирования')
      }
    }
  }
}
</script>

<style scoped>
.admin-blocked-devices {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.stats {
  display: flex;
  gap: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 2em;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9em;
  opacity: 0.9;
}

.search-filters {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 15px;
}

.search-bar input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
}

.filters {
  display: flex;
  gap: 15px;
}

.filters select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: white;
  min-width: 150px;
}

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

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

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.device-id {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-id code {
  background: #f1f3f4;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: monospace;
}

.copy-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.copy-btn:hover {
  opacity: 1;
}

.reason-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.85em;
  font-weight: 500;
}

.reason-badge.multiple_violations {
  background: #fee2e2;
  color: #dc2626;
}

.reason-badge.spam {
  background: #fef3c7;
  color: #d97706;
}

.reason-badge.harassment {
  background: #fecaca;
  color: #dc2626;
}

.reason-badge.fake_profile {
  background: #e0e7ff;
  color: #3730a3;
}

.reason-badge.other {
  background: #f3f4f6;
  color: #374151;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.85em;
  font-weight: 500;
}

.status-badge.active {
  background: #fecaca;
  color: #dc2626;
}

.status-badge.expired {
  background: #f3f4f6;
  color: #6b7280;
}

.permanent {
  color: #dc2626;
  font-weight: 500;
}

.expired {
  color: #6b7280;
  text-decoration: line-through;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-outline {
  background: white;
  border: 1px solid #ddd;
  color: #333;
}

.btn-outline:hover {
  background: #f8f9fa;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

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

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.page-info {
  color: #666;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.no-data-icon {
  font-size: 4em;
  margin-bottom: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 10px;
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  overflow: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.device-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-row {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.detail-row label {
  font-weight: 600;
  color: #333;
}

.detail-row code {
  background: #f1f3f4;
  padding: 8px;
  border-radius: 4px;
  font-family: monospace;
  word-break: break-all;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .filters {
    flex-direction: column;
  }

  .devices-table {
    overflow-x: auto;
  }

  table {
    min-width: 800px;
  }

  .actions {
    flex-direction: column;
  }
}
</style>