<template>
  <div class="admin">
    <div class="header">
      <h2>Video Library</h2>
      <div v-if="stats" class="stats">
        📊 {{ stats.total_videos }} videos · {{ stats.total_size_human }}
      </div>
    </div>

    <div class="search-bar">
      <input v-model="search" placeholder="Search videos..." @input="debouncedFetch" />
      <select v-model="filterStatus" @change="fetchVideos">
        <option value="">All Status</option>
        <option value="done">Done</option>
        <option value="downloading">Downloading</option>
        <option value="error">Error</option>
        <option value="pending">Pending</option>
      </select>
    </div>

    <div class="video-list">
      <div v-for="v in videos" :key="v.id" class="video-card">
        <div class="video-main">
          <img v-if="v.thumbnail" :src="v.thumbnail" class="thumb" />
          <div class="info">
            <h4>{{ v.title || 'Untitled' }}</h4>
            <div class="meta">
              <span :class="'status-' + v.status">{{ v.status }}</span>
              <span>{{ v.quality }}</span>
              <span>{{ humanSize(v.file_size) }}</span>
              <span>{{ new Date(v.created_at).toLocaleString() }}</span>
            </div>
          </div>
        </div>
        <div class="actions">
          <button v-if="v.status === 'done'" @click="playVideo(v)" class="btn-play">▶ Play</button>
          <a v-if="v.status === 'done'" :href="'/api/file/' + v.id" class="btn-dl"
             :download="v.filename" @click.prevent="downloadAuth(v)">💾</a>
          <button @click="deleteVideo(v)" class="btn-del">🗑</button>
        </div>
      </div>
      <div v-if="!videos.length" class="empty">No videos found</div>
    </div>

    <div v-if="totalPages > 1" class="pagination">
      <button :disabled="page <= 1" @click="page--; fetchVideos()">Prev</button>
      <span>{{ page }} / {{ totalPages }}</span>
      <button :disabled="page >= totalPages" @click="page++; fetchVideos()">Next</button>
    </div>

    <!-- Video Player Modal -->
    <div v-if="playing" class="modal" @click.self="playing = null">
      <div class="player-wrap">
        <video :src="playUrl" controls autoplay class="player"></video>
        <button @click="playing = null" class="close-btn">✕</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { useAuthStore } from '../stores/auth.js'

const auth = useAuthStore()
const videos = ref([])
const stats = ref(null)
const search = ref('')
const filterStatus = ref('')
const page = ref(1)
const total = ref(0)
const pageSize = 20
const playing = ref(null)
const playUrl = ref('')

const totalPages = computed(() => Math.ceil(total.value / pageSize) || 1)

function humanSize(bytes) {
  if (!bytes) return '0 B'
  for (const u of ['B', 'KB', 'MB', 'GB']) {
    if (bytes < 1024) return `${bytes.toFixed(1)} ${u}`
    bytes /= 1024
  }
  return `${bytes.toFixed(1)} TB`
}

let debounceTimer
function debouncedFetch() {
  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => { page.value = 1; fetchVideos() }, 300)
}

async function fetchVideos() {
  try {
    const res = await axios.get('/api/admin/videos', {
      params: { page: page.value, page_size: pageSize, search: search.value, status: filterStatus.value },
      headers: auth.getHeaders()
    })
    videos.value = res.data.videos
    total.value = res.data.total
  } catch (e) {
    if (e.response?.status === 401) { auth.logout(); location.href = '/login' }
  }
}

async function fetchStats() {
  try {
    const res = await axios.get('/api/admin/stats', { headers: auth.getHeaders() })
    stats.value = res.data
  } catch {}
}

function playVideo(v) {
  playing.value = v
  playUrl.value = `/api/stream/${v.id}?token=${auth.token}`
}

async function downloadAuth(v) {
  const res = await axios.get(`/api/file/${v.id}`, { headers: auth.getHeaders(), responseType: 'blob' })
  const url = URL.createObjectURL(res.data)
  const a = document.createElement('a'); a.href = url; a.download = v.filename; a.click()
  URL.revokeObjectURL(url)
}

async function deleteVideo(v) {
  if (!confirm(`Delete "${v.title}"?`)) return
  try {
    await axios.delete(`/api/admin/videos/${v.id}`, { headers: auth.getHeaders() })
    fetchVideos(); fetchStats()
  } catch (e) {
    alert('Delete failed')
  }
}

onMounted(() => { fetchVideos(); fetchStats() })
</script>

<style scoped>
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; }
.stats { color: #888; }
.search-bar { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.search-bar input { flex: 1; padding: 0.6rem 1rem; border: 1px solid #444; border-radius: 8px; background: #1a1a2e; color: #fff; }
.search-bar select { padding: 0.6rem; border: 1px solid #444; border-radius: 8px; background: #1a1a2e; color: #fff; }
.video-card {
  display: flex; justify-content: space-between; align-items: center;
  background: #1a1a2e; border-radius: 10px; padding: 1rem; margin-bottom: 0.8rem;
  gap: 1rem;
}
.video-main { display: flex; gap: 1rem; flex: 1; min-width: 0; }
.thumb { width: 80px; height: 45px; object-fit: cover; border-radius: 6px; flex-shrink: 0; }
.info { min-width: 0; }
.info h4 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 0.3rem; }
.meta { display: flex; gap: 0.8rem; font-size: 0.85rem; color: #888; flex-wrap: wrap; }
.status-done { color: #27ae60; }
.status-downloading { color: #f39c12; }
.status-error { color: #e74c3c; }
.status-pending { color: #888; }
.actions { display: flex; gap: 0.4rem; flex-shrink: 0; }
.actions button, .actions a {
  padding: 0.4rem 0.6rem; border: 1px solid #444; border-radius: 6px;
  background: transparent; color: #fff; cursor: pointer; text-decoration: none; font-size: 0.9rem;
}
.actions button:hover, .actions a:hover { border-color: #1da1f2; }
.btn-del:hover { border-color: #e74c3c !important; }
.empty { text-align: center; color: #666; padding: 3rem; }
.pagination { display: flex; justify-content: center; align-items: center; gap: 1rem; margin-top: 1.5rem; }
.pagination button { padding: 0.5rem 1rem; border: 1px solid #444; border-radius: 6px; background: transparent; color: #fff; cursor: pointer; }
.pagination button:disabled { opacity: 0.3; cursor: not-allowed; }
.modal { position: fixed; inset: 0; background: rgba(0,0,0,0.9); display: flex; align-items: center; justify-content: center; z-index: 999; }
.player-wrap { position: relative; max-width: 90vw; max-height: 90vh; }
.player { max-width: 90vw; max-height: 85vh; border-radius: 8px; }
.close-btn { position: absolute; top: -40px; right: 0; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
</style>
