<template>
  <div class="w-full animate-reveal">
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-serif italic text-white">分类管理</h1>
      <button @click="router.push('/admin/categories/create')" class="admin-btn-primary flex items-center gap-2">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
        新建分类
      </button>
    </div>

    <AdminTableFilter
      v-model:keyword="keyword"
      keyword-placeholder="搜索名称或 Slug..."
      @search="applyFilter"
      @reset="resetFilters"
    />
    
    <div class="admin-card overflow-hidden">
      <div class="overflow-x-auto">
        <table class="admin-table">
          <thead>
            <tr>
              <th class="w-20">ID</th>
              <th>名称</th>
              <th>Slug</th>
              <th>描述</th>
              <th>排序</th>
              <th>创建时间</th>
              <th class="text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="category in filteredCategories" :key="category.id" class="group transition-colors duration-200">
              <td class="font-mono text-xs text-white/40">#{{ category.id }}</td>
              <td class="font-medium text-white group-hover:text-art-accent transition-colors">{{ category.name }}</td>
              <td class="text-xs text-art-muted font-mono">{{ category.slug }}</td>
              <td class="text-sm text-white/70 max-w-xs truncate">{{ category.description || '-' }}</td>
              <td class="text-xs text-art-muted">{{ category.sortOrder }}</td>
              <td class="text-art-muted text-xs">{{ category.createdAt }}</td>
              <td class="text-right">
                <div class="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                  <router-link :to="`/admin/categories/${category.id}/edit`" class="admin-btn-secondary py-1 px-3 text-xs">
                    编辑
                  </router-link>
                  <button @click="handleDelete(category.id)" class="admin-btn-danger py-1 px-3 text-xs">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div v-if="filteredCategories.length === 0" class="p-16 text-center">
        <div class="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl">📂</div>
        <h3 class="text-white font-medium mb-2">暂无分类</h3>
        <p class="text-art-muted text-sm mb-6">创建分类来整理您的文章</p>
        <router-link to="/admin/categories/create" class="admin-btn-secondary inline-flex items-center gap-2">
          + 新建分类
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getAdminCategories, deleteCategory, Category } from '../../services/api'
import { useToast } from '../../composables/useToast'
import { useAppliedKeyword, matchKeywordFn } from '../../composables/useLocalTableFilter'
import AdminTableFilter from '../../components/admin/AdminTableFilter.vue'

const router = useRouter()
const toast = useToast()
const categories = ref<Category[]>([])
const { keyword, appliedKeyword, apply, reset } = useAppliedKeyword()

const filteredCategories = computed(() => categories.value.filter(c =>
  matchKeywordFn(c, appliedKeyword.value, item => `${item.name} ${item.slug || ''} ${item.description || ''}`)
))

const applyFilter = () => apply()
const resetFilters = () => reset()

const fetchCategories = async () => {
  try {
    categories.value = await getAdminCategories()
  } catch (error) {
    console.error('Error fetching categories:', error)
    toast.showToast('获取分类列表失败', 'error')
  }
}

const handleDelete = async (id: number) => {
  if (confirm('确定要删除这个分类吗？')) {
    try {
      await deleteCategory(id)
      toast.showToast('分类删除成功', 'success')
      fetchCategories()
    } catch (error) {
      console.error('Error deleting category:', error)
      toast.showToast('删除分类失败', 'error')
    }
  }
}

onMounted(() => {
  fetchCategories()
})
</script>
