<template>
  <div class="w-full animate-reveal">
    <!-- 悬浮顶栏：滚动时取消/保存始终可见 -->
    <div class="sticky top-0 z-20 -mx-6 px-6 py-4 mb-4 bg-art-admin-bg/95 backdrop-blur-md border-b border-white/5 flex items-center justify-between">
      <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/videos')">取消</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.title" 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-2">所属专辑（可多选）</label>
        <div v-if="albums.length" class="max-h-48 overflow-y-auto space-y-2 border border-white/10 rounded-lg p-3">
          <label v-for="a in albums" :key="a.id" class="flex items-center gap-3 p-2 rounded hover:bg-white/5 cursor-pointer">
            <input type="checkbox" :value="a.id" v-model="selectedAlbumIds" />
            <span class="text-sm text-white">{{ a.name }}</span>
            <span v-if="a.categoryName" class="text-xs text-art-muted">({{ a.categoryName }})</span>
          </label>
        </div>
        <p v-else class="text-xs text-art-muted">暂无专辑，请先在「视频专辑」中创建</p>
      </div>
      <div><label class="block text-xs text-art-muted mb-1">视频文件</label><VideoUpload v-model="form.videoUrl" :category-id="1" /></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="4" class="admin-input resize-none" /></div>
      <div><label class="block text-xs text-art-muted mb-1">发布状态</label>
        <select v-model.number="form.isPublished" class="admin-input w-40"><option :value="1">发布</option><option :value="0">草稿</option></select>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAdminVideoCategories, getAdminVideoAlbums, getAdminVideo, createVideo, updateVideo, type VideoAlbum } from '../../services/api'
import { useToast } from '../../composables/useToast'
import ImageUpload from '../../components/admin/ImageUpload.vue'
import VideoUpload from '../../components/admin/VideoUpload.vue'

const route = useRoute()
const router = useRouter()
const toast = useToast()
const submitting = ref(false)
const isEditing = computed(() => !!route.params.id)
const categories = ref<{ id: number; name: string }[]>([])
const albums = ref<VideoAlbum[]>([])
const selectedAlbumIds = ref<number[]>([])
const form = reactive({ title: '', description: '', videoUrl: '', cover: '', poster: '', categoryId: 0, isPublished: 1 })

onMounted(async () => {
  categories.value = await getAdminVideoCategories()
  albums.value = await getAdminVideoAlbums()
  if (isEditing.value) {
    const item = await getAdminVideo(route.params.id as string)
    Object.assign(form, {
      title: item.title,
      description: item.description,
      videoUrl: item.videoUrl,
      cover: item.cover,
      poster: item.poster,
      categoryId: item.categoryId,
      isPublished: item.isPublished,
    })
    selectedAlbumIds.value = item.albumIds ?? []
  }
})

/** 提交视频表单，同步专辑关联 */
const handleSubmit = async () => {
  if (!form.videoUrl) { toast.error('请上传视频'); return }
  submitting.value = true
  try {
    form.poster = form.cover || form.poster
    const payload = { ...form, albumIds: selectedAlbumIds.value }
    if (isEditing.value) {
      await updateVideo(route.params.id as string, payload)
      toast.success('更新成功')
    } else {
      await createVideo(payload)
      toast.success('创建成功')
    }
    router.push('/admin/videos')
  } catch { toast.error('保存失败') } finally { submitting.value = false }
}
</script>
