<template>
  <div class="code-types-container">
    <h1 class="page-title">代码类型管理</h1>

    <div class="action-bar">
      <button class="btn-primary" @click="router.push('/admin/code-types/create')">
        <span class="btn-icon">➕</span>
        新建类型
      </button>
    </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: 120px;" />
        </div>
      </template>
    </AdminTableFilter>

    <div class="table-container">
      <table class="admin-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>名称</th>
            <th>分类</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in filteredItems" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>
              <span class="category-badge">{{ categoryLabel(item.category) }}</span>
            </td>
            <td class="actions">
              <button class="btn-edit" @click="router.push(`/admin/code-types/${item.id}/edit`)">✏️</button>
              <button class="btn-delete" @click="handleDelete(item.id)">🗑️</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="filteredItems.length === 0" class="empty-state">暂无匹配的代码类型</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getAdminCodeTypes, deleteCodeType, CODE_TYPE_CATEGORY_LABELS, type CodeType } 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 router = useRouter()
const toast = useToast()
const codeTypes = ref<CodeType[]>([])
const { keyword, appliedKeyword, apply, reset } = useAppliedKeyword()
const filterCategory = ref<number | string>('')
const appliedCategory = ref<number | string>('')

const categoryOptions = [
  { value: '', label: '全部分类' },
  ...Object.entries(CODE_TYPE_CATEGORY_LABELS).map(([k, v]) => ({ value: Number(k), label: v }))
]

const categoryLabel = (category: number) => CODE_TYPE_CATEGORY_LABELS[category] ?? '未知'

const filteredItems = computed(() => codeTypes.value.filter(item => {
  if (!matchKeywordFn(item, appliedKeyword.value, i => i.name)) return false
  if (appliedCategory.value !== '' && item.category !== Number(appliedCategory.value)) return false
  return true
}))

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

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

const fetchList = async () => {
  try {
    codeTypes.value = await getAdminCodeTypes()
  } catch (error) {
    console.error(error)
    toast.error('加载代码类型失败')
  }
}

const handleDelete = async (id: number) => {
  if (!confirm('确定删除该代码类型吗？')) return
  try {
    await deleteCodeType(id)
    toast.success('删除成功')
    fetchList()
  } catch (error: any) {
    toast.error(error.message || '删除失败')
  }
}

onMounted(fetchList)
</script>

<style scoped>
.code-types-container { width: 100%; }
.page-title { font-size: 1.75rem; font-weight: 600; color: #d4b383; margin-bottom: 1.5rem; }
.action-bar { margin-bottom: 1rem; }
.btn-primary { background: #d4b383; color: #050505; border: none; padding: 0.5rem 1rem; border-radius: 0.375rem; cursor: pointer; font-weight: 500; }
.table-container { background: rgba(255,255,255,0.05); border-radius: 0.5rem; border: 1px solid rgba(255,255,255,0.1); overflow: hidden; }
.admin-table { width: 100%; border-collapse: collapse; color: white; }
.admin-table th, .admin-table td { padding: 1rem; border-bottom: 1px solid rgba(255,255,255,0.1); text-align: left; }
.admin-table th { color: #d4b383; background: rgba(255,255,255,0.08); }
.category-badge { font-size: 0.75rem; color: #d4b383; }
.actions { display: flex; gap: 0.5rem; }
.btn-edit, .btn-delete { background: none; border: none; cursor: pointer; font-size: 1rem; }
.empty-state { padding: 2rem; text-align: center; color: rgba(255,255,255,0.5); }
</style>
