<template>
  <div class="w-full animate-reveal h-[calc(100vh-8rem)] flex flex-col">
    <!-- Top Bar -->
    <div class="flex items-center justify-between mb-4 shrink-0">
      <div class="flex items-center gap-4">
        <h1 class="text-2xl font-serif italic text-white">{{ isEditing ? '编辑分类' : '新建分类' }}</h1>
      </div>
      <div class="flex gap-3">
        <button type="button" class="admin-btn-secondary" @click="handleCancel">
          取消
        </button>
        <button type="button" class="admin-btn-primary" @click="handleSubmit" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : (isEditing ? '保存修改' : '创建分类') }}
        </button>
      </div>
    </div>

    <div class="admin-card p-6 max-w-2xl mx-auto w-full">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- Name Field -->
        <div class="space-y-2">
          <label for="name" class="block text-xs font-medium text-art-muted uppercase tracking-wider">名称</label>
          <input
              type="text"
              id="name"
              v-model="form.name"
              class="admin-input"
              placeholder="请输入分类名称"
              required
          />
        </div>

        <!-- Slug Field -->
        <div class="space-y-2">
          <label for="slug" class="block text-xs font-medium text-art-muted uppercase tracking-wider">Slug (URL标识)</label>
          <input
              type="text"
              id="slug"
              v-model="form.slug"
              class="admin-input font-mono"
              placeholder="category-slug"
              required
          />
        </div>

        <!-- Sort Order Field -->
        <div class="space-y-2">
          <label for="sortOrder" class="block text-xs font-medium text-art-muted uppercase tracking-wider">排序 (越小越靠前)</label>
          <input
              type="number"
              id="sortOrder"
              v-model="form.sortOrder"
              class="admin-input"
              placeholder="0"
          />
        </div>

        <!-- Description Field -->
        <div class="space-y-2">
          <label for="description" class="block text-xs font-medium text-art-muted uppercase tracking-wider">描述</label>
          <textarea
              id="description"
              v-model="form.description"
              rows="4"
              class="admin-input resize-none"
              placeholder="简短的分类描述..."
          ></textarea>
        </div>
      </form>
    </div>
  </div>
</template>

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

const router = useRouter()
const route = useRoute()
const toast = useToast()

const isSubmitting = ref(false)
const isEditing = computed(() => !!route.params.id)

const form = reactive({
  name: '',
  slug: '',
  description: '',
  sortOrder: 0
})

const handleSubmit = async () => {
  if (!form.name.trim() || !form.slug.trim()) {
    toast.showToast('名称和Slug不能为空', 'error')
    return
  }

  isSubmitting.value = true

  try {
    if (isEditing.value) {
      const id = parseInt(route.params.id as string)
      await updateCategory(id, form)
      toast.showToast('分类更新成功', 'success')
    } else {
      await createCategory(form)
      toast.showToast('分类创建成功', 'success')
    }
    router.push('/admin/categories')
  } catch (error: any) {
    console.error('Error submitting form:', error)
    toast.showToast(error.message || (isEditing.value ? '更新分类失败' : '创建分类失败'), 'error')
  } finally {
    isSubmitting.value = false
  }
}

const handleCancel = () => {
  router.back()
}

onMounted(async () => {
  if (isEditing.value) {
    try {
      const id = parseInt(route.params.id as string)
      // Note: We don't have getCategoryById in API for single category yet, 
      // but we can fetch all and find one, or update API.
      // For now, let's fetch all (simple enough for admin)
      const categories = await getAdminCategories()
      const category = categories.find(c => c.id === id)
      if (category) {
        form.name = category.name
        form.slug = category.slug
        form.description = category.description
        form.sortOrder = category.sortOrder
      } else {
        toast.showToast('未找到该分类', 'error')
        router.push('/admin/categories')
      }
    } catch (error) {
      console.error('Failed to load category:', error)
      toast.showToast('加载数据失败', 'error')
    }
  }
})
</script>
