<template>
  <div class="manager-page">
    <h1>Backgrounds Manager</h1>
    <p class="subtitle">Manage background videos for different difficulties</p>

    <!-- Header Actions -->
    <div class="header-actions">
      <div class="filters">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="Search by name..."
          class="search-input"
        />
        <select v-model="filterDifficulty" class="filter-select">
          <option value="">All Difficulties</option>
          <option value="easy">Easy</option>
          <option value="medium">Medium</option>
          <option value="hard">Hard</option>
        </select>
      </div>
      <button class="btn-primary" @click="openCreateModal">+ Add Background</button>
    </div>

    <!-- Stats -->
    <div class="stats-bar">
      <div class="stat-item easy">
        <span class="stat-value">{{ countByDifficulty('easy') }}</span>
        <span class="stat-label">Easy</span>
      </div>
      <div class="stat-item medium">
        <span class="stat-value">{{ countByDifficulty('medium') }}</span>
        <span class="stat-label">Medium</span>
      </div>
      <div class="stat-item hard">
        <span class="stat-value">{{ countByDifficulty('hard') }}</span>
        <span class="stat-label">Hard</span>
      </div>
      <div class="stat-item total">
        <span class="stat-value">{{ total }}</span>
        <span class="stat-label">Total</span>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <span>Loading backgrounds...</span>
    </div>

    <!-- Empty State -->
    <div v-else-if="backgrounds.length === 0" class="empty-state">
      <span class="empty-icon">🎬</span>
      <p>No backgrounds found</p>
      <button class="btn-primary" @click="openCreateModal">Add your first background</button>
    </div>

    <!-- Backgrounds Grid -->
    <div v-else class="backgrounds-grid">
      <div
        v-for="bg in backgrounds"
        :key="bg.id"
        class="background-card"
        :class="'difficulty-' + bg.difficulty"
      >
        <div class="background-preview">
          <span class="video-icon">🎬</span>
          <span class="video-file">{{ bg.video_file }}</span>
        </div>
        <div class="background-info">
          <h3 class="bg-name">{{ bg.name }}</h3>
          <span class="difficulty-badge" :class="bg.difficulty">{{ bg.difficulty.toUpperCase() }}</span>
        </div>
        <div class="background-actions">
          <button class="btn-icon" @click="openEditModal(bg)" title="Edit">✏️</button>
          <button class="btn-icon btn-delete" @click="confirmDelete(bg)" title="Delete">🗑️</button>
        </div>
      </div>
    </div>

    <!-- Create/Edit Modal -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal">
        <div class="modal-header">
          <h2>{{ editingBackground ? 'Edit Background' : 'Add Background' }}</h2>
          <button class="modal-close" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Name *</label>
            <input type="text" v-model="form.name" placeholder="e.g., Calm Ocean" />
          </div>
          <div class="form-group">
            <label>Video File (S3 key) *</label>
            <select v-model="form.video_file">
              <option value="">Select video file...</option>
              <option v-for="file in videoFiles" :key="file" :value="file">{{ file }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>Difficulty *</label>
            <div class="difficulty-selector">
              <button
                type="button"
                class="diff-btn easy"
                :class="{ active: form.difficulty === 'easy' }"
                @click="form.difficulty = 'easy'"
              >
                Easy
              </button>
              <button
                type="button"
                class="diff-btn medium"
                :class="{ active: form.difficulty === 'medium' }"
                @click="form.difficulty = 'medium'"
              >
                Medium
              </button>
              <button
                type="button"
                class="diff-btn hard"
                :class="{ active: form.difficulty === 'hard' }"
                @click="form.difficulty = 'hard'"
              >
                Hard
              </button>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" @click="closeModal">Cancel</button>
          <button class="btn-primary" @click="saveBackground" :disabled="saving">
            {{ saving ? 'Saving...' : (editingBackground ? 'Update' : 'Create') }}
          </button>
        </div>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
      <div class="delete-modal">
        <h3>Confirm Delete</h3>
        <p>Are you sure you want to delete this background?</p>
        <div class="delete-preview">
          <strong>{{ deletingBackground?.name }}</strong>
          <span class="difficulty-badge" :class="deletingBackground?.difficulty">
            {{ deletingBackground?.difficulty?.toUpperCase() }}
          </span>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showDeleteModal = false">Cancel</button>
          <button class="btn-delete-confirm" @click="executeDelete">Delete</button>
        </div>
      </div>
    </div>

    <!-- Toast Notifications -->
    <div class="toast-container">
      <div v-for="(t, index) in toasts" :key="index" class="toast" :class="t.type">
        {{ t.message }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'

export default {
  name: 'BackgroundsManager',
  setup() {
    const backgrounds = ref([])
    const allBackgrounds = ref([])
    const total = ref(0)
    const loading = ref(true)
    const saving = ref(false)
    const searchQuery = ref('')
    const filterDifficulty = ref('')
    const toasts = ref([])

    // Modal states
    const showModal = ref(false)
    const showDeleteModal = ref(false)
    const editingBackground = ref(null)
    const deletingBackground = ref(null)

    // Form data
    const form = reactive({
      name: '',
      video_file: '',
      difficulty: 'medium'
    })

    // Available files from S3
    const videoFiles = ref([])

    const countByDifficulty = (difficulty) => {
      return allBackgrounds.value.filter(bg => bg.difficulty === difficulty).length
    }

    const showToast = (message, type = 'success') => {
      const toast = { message, type }
      toasts.value.push(toast)
      setTimeout(() => {
        const idx = toasts.value.indexOf(toast)
        if (idx > -1) toasts.value.splice(idx, 1)
      }, 3000)
    }

    const fetchBackgrounds = async () => {
      loading.value = true
      try {
        const params = new URLSearchParams()
        if (searchQuery.value) params.append('search', searchQuery.value)
        if (filterDifficulty.value) params.append('difficulty', filterDifficulty.value)

        const response = await fetch(`/api/api/backgrounds?${params}`)
        const data = await response.json()
        backgrounds.value = data.backgrounds
        total.value = data.total

        // Also fetch all for stats
        const allResponse = await fetch('/api/api/backgrounds')
        const allData = await allResponse.json()
        allBackgrounds.value = allData.backgrounds
      } catch (e) {
        showToast('Failed to fetch backgrounds', 'error')
      } finally {
        loading.value = false
      }
    }

    const fetchContent = async () => {
      try {
        const response = await fetch('/api/content')
        const data = await response.json()
        videoFiles.value = data.background_videos || []
      } catch (e) {
        console.error('Failed to fetch content:', e)
      }
    }

    const openCreateModal = () => {
      editingBackground.value = null
      form.name = ''
      form.video_file = ''
      form.difficulty = 'medium'
      showModal.value = true
    }

    const openEditModal = (bg) => {
      editingBackground.value = bg
      form.name = bg.name
      form.video_file = bg.video_file
      form.difficulty = bg.difficulty
      showModal.value = true
    }

    const closeModal = () => {
      showModal.value = false
      editingBackground.value = null
    }

    const saveBackground = async () => {
      if (!form.name || !form.video_file) {
        showToast('Please fill all required fields', 'error')
        return
      }

      saving.value = true
      try {
        const payload = {
          name: form.name,
          video_file: form.video_file,
          difficulty: form.difficulty
        }

        if (editingBackground.value) {
          // Update
          await fetch(`/api/api/backgrounds/${editingBackground.value.id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          })
          showToast('Background updated')
        } else {
          // Create
          await fetch('/api/api/backgrounds', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          })
          showToast('Background created')
        }

        closeModal()
        await fetchBackgrounds()
      } catch (e) {
        showToast('Failed to save background', 'error')
      } finally {
        saving.value = false
      }
    }

    const confirmDelete = (bg) => {
      deletingBackground.value = bg
      showDeleteModal.value = true
    }

    const executeDelete = async () => {
      if (!deletingBackground.value) return

      try {
        await fetch(`/api/api/backgrounds/${deletingBackground.value.id}`, {
          method: 'DELETE'
        })
        showToast('Background deleted')
        showDeleteModal.value = false
        deletingBackground.value = null
        await fetchBackgrounds()
      } catch (e) {
        showToast('Failed to delete background', 'error')
      }
    }

    // Search/filter with debounce
    let searchTimeout
    watch([searchQuery, filterDifficulty], () => {
      clearTimeout(searchTimeout)
      searchTimeout = setTimeout(fetchBackgrounds, 300)
    })

    onMounted(() => {
      fetchBackgrounds()
      fetchContent()
    })

    return {
      backgrounds,
      total,
      loading,
      saving,
      searchQuery,
      filterDifficulty,
      toasts,
      showModal,
      showDeleteModal,
      editingBackground,
      deletingBackground,
      form,
      videoFiles,
      countByDifficulty,
      openCreateModal,
      openEditModal,
      closeModal,
      saveBackground,
      confirmDelete,
      executeDelete
    }
  }
}
</script>

<style scoped>
.manager-page {
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.manager-page h1 {
  text-align: center;
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  background: linear-gradient(90deg, #00d4ff, #7b2cbf);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  text-align: center;
  color: #888;
  margin-bottom: 2rem;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.filters {
  display: flex;
  gap: 1rem;
  flex: 1;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  max-width: 300px;
  padding: 0.75rem 1rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  font-size: 1rem;
}

.search-input:focus {
  outline: none;
  border-color: #00d4ff;
}

.filter-select {
  padding: 0.75rem 1rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  font-size: 1rem;
  min-width: 150px;
}

.filter-select:focus {
  outline: none;
  border-color: #00d4ff;
}

.btn-primary {
  padding: 0.75rem 1.5rem;
  background: linear-gradient(90deg, #00d4ff, #7b2cbf);
  border: none;
  border-radius: 8px;
  color: #fff;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

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

.stats-bar {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255, 255, 255, 0.05);
  padding: 1rem 2rem;
  border-radius: 12px;
  border: 2px solid transparent;
}

.stat-item.easy {
  border-color: rgba(0, 255, 136, 0.3);
}

.stat-item.medium {
  border-color: rgba(255, 170, 0, 0.3);
}

.stat-item.hard {
  border-color: rgba(255, 68, 68, 0.3);
}

.stat-item.total {
  border-color: rgba(0, 212, 255, 0.3);
}

.stat-item.easy .stat-value { color: #00ff88; }
.stat-item.medium .stat-value { color: #ffaa00; }
.stat-item.hard .stat-value { color: #ff4444; }
.stat-item.total .stat-value { color: #00d4ff; }

.stat-value {
  font-size: 2rem;
  font-weight: 700;
}

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

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  padding: 3rem;
  color: #888;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 212, 255, 0.3);
  border-top-color: #00d4ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 4rem;
  color: #666;
}

.empty-icon {
  font-size: 4rem;
  display: block;
  margin-bottom: 1rem;
}

.empty-state p {
  margin-bottom: 1.5rem;
}

/* Backgrounds Grid */
.backgrounds-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.background-card {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 16px;
  overflow: hidden;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.background-card:hover {
  transform: translateY(-4px);
}

.background-card.difficulty-easy {
  border-color: rgba(0, 255, 136, 0.3);
}

.background-card.difficulty-medium {
  border-color: rgba(255, 170, 0, 0.3);
}

.background-card.difficulty-hard {
  border-color: rgba(255, 68, 68, 0.3);
}

.background-card:hover.difficulty-easy {
  border-color: #00ff88;
}

.background-card:hover.difficulty-medium {
  border-color: #ffaa00;
}

.background-card:hover.difficulty-hard {
  border-color: #ff4444;
}

.background-preview {
  height: 120px;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.video-icon {
  font-size: 2.5rem;
}

.video-file {
  color: #666;
  font-size: 0.75rem;
  max-width: 90%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.background-info {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bg-name {
  font-size: 1.1rem;
  color: #fff;
  margin: 0;
}

.difficulty-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 600;
}

.difficulty-badge.easy {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
}

.difficulty-badge.medium {
  background: rgba(255, 170, 0, 0.2);
  color: #ffaa00;
}

.difficulty-badge.hard {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.background-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  padding: 0 1rem 1rem;
}

.btn-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  border: none;
  background: rgba(255, 255, 255, 0.1);
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s ease;
}

.btn-icon:hover {
  background: rgba(255, 255, 255, 0.2);
}

.btn-icon.btn-delete {
  background: rgba(255, 68, 68, 0.2);
}

.btn-icon.btn-delete:hover {
  background: rgba(255, 68, 68, 0.3);
}

/* Modal */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

.modal {
  background: #1a1a2e;
  border-radius: 16px;
  width: 100%;
  max-width: 500px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h2 {
  color: #00d4ff;
  font-size: 1.25rem;
}

.modal-close {
  background: none;
  border: none;
  color: #888;
  font-size: 1.5rem;
  cursor: pointer;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #ccc;
  font-size: 0.9rem;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  font-size: 0.95rem;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #00d4ff;
}

.difficulty-selector {
  display: flex;
  gap: 0.75rem;
}

.diff-btn {
  flex: 1;
  padding: 0.75rem;
  border-radius: 8px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  background: transparent;
  color: #888;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.diff-btn.easy:hover,
.diff-btn.easy.active {
  border-color: #00ff88;
  color: #00ff88;
  background: rgba(0, 255, 136, 0.1);
}

.diff-btn.medium:hover,
.diff-btn.medium.active {
  border-color: #ffaa00;
  color: #ffaa00;
  background: rgba(255, 170, 0, 0.1);
}

.diff-btn.hard:hover,
.diff-btn.hard.active {
  border-color: #ff4444;
  color: #ff4444;
  background: rgba(255, 68, 68, 0.1);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.btn-cancel {
  padding: 0.75rem 1.5rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: #fff;
  cursor: pointer;
}

.btn-cancel:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* Delete Modal */
.delete-modal {
  background: #1a1a2e;
  border-radius: 16px;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.delete-modal h3 {
  color: #ff4444;
  margin-bottom: 0.5rem;
}

.delete-modal p {
  color: #888;
  margin-bottom: 1.5rem;
}

.delete-preview {
  background: rgba(0, 0, 0, 0.3);
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn-delete-confirm {
  padding: 0.75rem 1.5rem;
  background: #ff4444;
  border: none;
  border-radius: 8px;
  color: #fff;
  cursor: pointer;
  font-weight: 500;
}

.btn-delete-confirm:hover {
  background: #ff2222;
}

/* Toast */
.toast-container {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  z-index: 1001;
}

.toast {
  padding: 1rem 1.5rem;
  border-radius: 8px;
  color: #fff;
  font-weight: 500;
  animation: slideIn 0.3s ease;
}

.toast.success {
  background: linear-gradient(90deg, #00d4ff, #00a8cc);
}

.toast.error {
  background: linear-gradient(90deg, #ff4444, #cc2222);
}

@keyframes slideIn {
  from { transform: translateX(100%); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}

@media (max-width: 768px) {
  .manager-page {
    padding: 1rem;
  }

  .header-actions {
    flex-direction: column;
  }

  .filters {
    width: 100%;
  }

  .search-input {
    max-width: 100%;
  }

  .backgrounds-grid {
    grid-template-columns: 1fr;
  }

  .stats-bar {
    gap: 0.75rem;
  }

  .stat-item {
    padding: 0.75rem 1rem;
  }
}
</style>
