<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>
      <router-link to="/admin/works/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>
        新增作品
      </router-link>
    </div>

    <AdminTableFilter
      v-model:keyword="keyword"
      keyword-placeholder="搜索作品标题..."
      @search="applyFilter"
      @reset="resetFilters"
    >
      <template #filters>
        <div class="filter-field">
          <label>分类</label>
          <CustomSelect v-model="filterCategory" :options="categoryOptions" style="width: 140px;" />
        </div>
        <div class="filter-field">
          <label>年份</label>
          <CustomSelect v-model="filterYear" :options="yearOptions" style="width: 100px;" />
        </div>
      </template>
    </AdminTableFilter>
    
    <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>分类</th>
              <th>年份</th>
              <th class="text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="work in filteredWorks" :key="work.id" class="group transition-colors duration-200">
              <td class="font-mono text-xs text-white/40">#{{ work.id }}</td>
              <td class="font-medium text-white group-hover:text-art-accent transition-colors">{{ work.title }}</td>
              <td><span class="px-2 py-1 rounded bg-white/5 border border-white/5 text-xs text-art-muted">{{ work.category }}</span></td>
              <td class="text-art-muted text-xs">{{ work.year }}</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/works/${work.id}/edit`" class="admin-btn-secondary py-1 px-3 text-xs">
                    编辑
                  </router-link>
                  <button @click="deleteWork(work.id)" class="admin-btn-danger py-1 px-3 text-xs">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div v-if="filteredWorks.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/works/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 { getAdminWorks, deleteWork as deleteWorkApi, Work } from '../../services/api'
import { useToast } from '../../composables/useToast'
import { useAppliedKeyword, matchKeywordFn } from '../../composables/useLocalTableFilter'
import AdminTableFilter from '../../components/admin/AdminTableFilter.vue'
import CustomSelect from '../../components/CustomSelect.vue'

const toast = useToast()
const works = ref<Work[]>([])
const { keyword, appliedKeyword, apply, reset } = useAppliedKeyword()
const filterCategory = ref('')
const filterYear = ref('')
const appliedCategory = ref('')
const appliedYear = ref('')

const categoryOptions = computed(() => {
  const cats = [...new Set(works.value.map(w => w.category).filter(Boolean))]
  return [{ value: '', label: '全部分类' }, ...cats.map(c => ({ value: c, label: c }))]
})

const yearOptions = computed(() => {
  const years = [...new Set(works.value.map(w => w.year).filter(Boolean))].sort().reverse()
  return [{ value: '', label: '全部年份' }, ...years.map(y => ({ value: y, label: y }))]
})

const filteredWorks = computed(() => works.value.filter(w => {
  if (!matchKeywordFn(w, appliedKeyword.value, item => item.title)) return false
  if (appliedCategory.value && w.category !== appliedCategory.value) return false
  if (appliedYear.value && w.year !== appliedYear.value) return false
  return true
}))

const applyFilter = () => {
  apply()
  appliedCategory.value = filterCategory.value
  appliedYear.value = filterYear.value
}

const resetFilters = () => {
  reset()
  filterCategory.value = ''
  filterYear.value = ''
  appliedCategory.value = ''
  appliedYear.value = ''
}

const fetchWorks = async () => {
  try {
    const result = await getAdminWorks()
    // 确保 works.value 始终是数组
    works.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('Error fetching works:', error)
    toast.showToast('获取作品列表失败', 'error')
    // 确保错误时也保持为空数组
    works.value = []
  }
}

const deleteWork = async (id: string) => {
  if (confirm('确定要删除这个作品吗？')) {
    try {
      await deleteWorkApi(id)
      toast.showToast('作品删除成功', 'success')
      fetchWorks()
    } catch (error) {
      console.error('Error deleting work:', error)
      toast.showToast('删除作品失败', 'error')
    }
  }
}

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

<style scoped>
/* Scoped styles removed */
</style>
