<template>
  <div class="admin-snippets">
    <h1 class="page-title">代码片段管理</h1>
    
    <div class="toolbar">
      <router-link to="/admin/snippets/create" class="btn btn-primary">
        + 新增代码片段
      </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="filterCodeTypeId" :options="codeTypeOptions" style="width: 140px;" />
        </div>
      </template>
    </AdminTableFilter>
    
    <div class="table-container">
      <table class="admin-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>标题</th>
            <th>类型</th>
            <th>查看次数</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="snippet in filteredSnippets" :key="snippet.id">
            <td>{{ snippet.id }}</td>
            <td>{{ snippet.title }}</td>
            <td>
              <span class="type-badge">{{ snippet.codeType?.name || snippet.type }}</span>
            </td>
            <td>{{ snippet.viewCount || 0 }}</td>
            <td class="actions">
              <router-link :to="`/admin/snippets/${snippet.id}/edit`" class="btn btn-sm btn-secondary">
                编辑
              </router-link>
              <button @click="deleteSnippet(snippet.id)" class="btn btn-sm btn-danger">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <div v-if="filteredSnippets.length === 0" class="empty-state">
      <p>{{ appliedKeyword || filterCodeTypeId ? '没有匹配的代码片段' : '暂无代码片段，请点击上方按钮新增' }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getAdminSnippets, getAdminCodeTypes, deleteSnippet as deleteSnippetApi, type Snippet, 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 toast = useToast()
const snippets = ref<Snippet[]>([])
const codeTypes = ref<CodeType[]>([])
const { keyword, appliedKeyword, apply, reset } = useAppliedKeyword()
const filterCodeTypeId = ref<number | string>(0)
const appliedCodeTypeId = ref(0)

const codeTypeOptions = computed(() => [
  { value: 0, label: '全部类型' },
  ...codeTypes.value.map(t => ({ value: t.id, label: t.name }))
])

const filteredSnippets = computed(() => {
  return snippets.value.filter(s => {
    if (!matchKeywordFn(s, appliedKeyword.value, item => item.title)) return false
    if (appliedCodeTypeId.value > 0 && s.codeTypeId !== appliedCodeTypeId.value) return false
    return true
  })
})

const applyFilter = () => {
  apply()
  appliedCodeTypeId.value = Number(filterCodeTypeId.value) || 0
}

const resetFilters = () => {
  reset()
  filterCodeTypeId.value = 0
  appliedCodeTypeId.value = 0
}

const fetchSnippets = async () => {
  try {
    snippets.value = await getAdminSnippets({ pageSize: 500 })
  } catch (error) {
    console.error('Error fetching snippets:', error)
    toast.error('获取代码片段列表失败')
  }
}

const deleteSnippet = async (id: number) => {
  if (confirm('确定要删除这个代码片段吗？')) {
    try {
      await deleteSnippetApi(id)
      toast.success('代码片段删除成功')
      fetchSnippets()
    } catch (error) {
      console.error('Error deleting snippet:', error)
      toast.error('删除代码片段失败')
    }
  }
}

onMounted(async () => {
  try {
    codeTypes.value = await getAdminCodeTypes()
  } catch { /* ignore */ }
  fetchSnippets()
})
</script>

<style scoped>
.admin-snippets {
  width: 100%;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #d4b383;
  margin-bottom: 1.5rem;
}

.toolbar {
  margin-bottom: 1rem;
}

.btn-primary {
  background: #d4b383;
  color: #050505;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  cursor: pointer;
  font-weight: 500;
  text-decoration: none;
  display: inline-block;
}

.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;
  text-align: left;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.admin-table th {
  background: rgba(255, 255, 255, 0.08);
  color: #d4b383;
  font-size: 0.875rem;
}

.type-badge {
  padding: 0.2rem 0.5rem;
  background: rgba(212, 179, 131, 0.15);
  border-radius: 0.25rem;
  font-size: 0.75rem;
  color: #d4b383;
}

.actions {
  display: flex;
  gap: 0.5rem;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
  border-radius: 0.25rem;
  cursor: pointer;
  border: none;
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  text-decoration: none;
}

.btn-danger {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.empty-state {
  padding: 2rem;
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
}
</style>
