<template>
  <div class="w-full animate-reveal">
    <div class="flex items-center justify-between mb-4">
      <h1 class="text-2xl font-serif italic text-white">{{ isEditing ? '编辑视频专辑' : '新建视频专辑' }}</h1>
      <div class="flex gap-3">
        <button type="button" class="admin-btn-secondary" @click="router.push('/admin/video-albums')">取消</button>
        <button type="button" class="admin-btn-primary" :disabled="submitting" @click="handleSubmit">{{ submitting ? '提交中...' : '保存' }}</button>
      </div>
    </div>
    <div class="admin-card p-6 max-w-3xl space-y-5">
      <div><label class="block text-xs text-art-muted mb-1">专辑名称</label><input v-model="form.name" class="admin-input" required /></div>
      <div><label class="block text-xs text-art-muted mb-1">所属分类</label>
        <select v-model.number="form.categoryId" class="admin-input">
          <option :value="0">未分类</option>
          <option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</option>
        </select>
      </div>
      <div><label class="block text-xs text-art-muted mb-1">封面</label><ImageUpload v-model="form.cover" :category-id="1" /></div>
      <div><label class="block text-xs text-art-muted mb-1">描述</label><textarea v-model="form.description" rows="3" class="admin-input resize-none" /></div>
      <div class="flex gap-6">
        <div><label class="block text-xs text-art-muted mb-1">排序</label><input v-model.number="form.sortOrder" type="number" class="admin-input w-32" /></div>
        <div><label class="block text-xs text-art-muted mb-1">状态</label>
          <select v-model.number="form.isActive" class="admin-input w-32"><option :value="1">启用</option><option :value="0">禁用</option></select>
        </div>
      </div>
      <div v-if="isEditing">
        <label class="block text-xs text-art-muted mb-2">专辑内视频（勾选加入专辑）</label>
        <div class="max-h-64 overflow-y-auto space-y-2 border border-white/10 rounded-lg p-3">
          <label v-for="v in allVideos" :key="v.id" class="flex items-center gap-3 p-2 rounded hover:bg-white/5 cursor-pointer">
            <input type="checkbox" :value="v.id" v-model="selectedVideoIds" />
            <span class="text-sm text-white">{{ v.title }}</span>
          </label>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getAdminVideoAlbums, getAdminVideoCategories, getAdminVideos, getAlbumVideoIds,
  createVideoAlbum, updateVideoAlbum, type VideoCategory, type VideoItem,
} from '../../services/api'
import { useToast } from '../../composables/useToast'
import ImageUpload from '../../components/admin/ImageUpload.vue'

const route = useRoute()
const router = useRouter()
const toast = useToast()
const submitting = ref(false)
const isEditing = computed(() => !!route.params.id)
const categories = ref<VideoCategory[]>([])
const allVideos = ref<VideoItem[]>([])
const selectedVideoIds = ref<string[]>([])
const form = reactive({ name: '', description: '', cover: '', categoryId: 0, isActive: 1, sortOrder: 0 })

onMounted(async () => {
  categories.value = await getAdminVideoCategories()
  allVideos.value = await getAdminVideos()
  if (isEditing.value) {
    const albums = await getAdminVideoAlbums()
    const item = albums.find(a => a.id === Number(route.params.id))
    if (item) Object.assign(form, { name: item.name, description: item.description, cover: item.cover, categoryId: item.categoryId, isActive: item.isActive, sortOrder: item.sortOrder })
    selectedVideoIds.value = await getAlbumVideoIds(Number(route.params.id))
  }
})

const handleSubmit = async () => {
  submitting.value = true
  try {
    const payload = { ...form, videoIds: selectedVideoIds.value }
    if (isEditing.value) {
      await updateVideoAlbum(Number(route.params.id), payload)
      toast.success('更新成功')
    } else {
      await createVideoAlbum(payload)
      toast.success('创建成功')
    }
    router.push('/admin/video-albums')
  } catch { toast.error('保存失败') } finally { submitting.value = false }
}
</script>
