<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-categories')">取消</button>
        <button type="button" class="admin-btn-primary" :disabled="submitting" @click="handleSubmit">{{ submitting ? '提交中...' : '保存' }}</button>
      </div>
    </div>
    <div class="admin-card p-6 max-w-2xl">
      <form class="space-y-5" @submit.prevent="handleSubmit">
        <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">Slug</label><input v-model="form.slug" class="admin-input font-mono" required /></div>
        <div><label class="block text-xs text-art-muted mb-1">排序</label><input v-model.number="form.sortOrder" type="number" class="admin-input" /></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>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAdminVideoCategories, createVideoCategory, updateVideoCategory } from '../../services/api'
import { useToast } from '../../composables/useToast'

const route = useRoute()
const router = useRouter()
const toast = useToast()
const submitting = ref(false)
const isEditing = computed(() => !!route.params.id)
const form = reactive({ name: '', slug: '', description: '', sortOrder: 0 })

onMounted(async () => {
  if (!isEditing.value) return
  const list = await getAdminVideoCategories()
  const item = list.find(c => c.id === Number(route.params.id))
  if (item) Object.assign(form, { name: item.name, slug: item.slug, description: item.description, sortOrder: item.sortOrder })
})

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