<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/columns/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="搜索专栏名称..."
      @search="applyFilter"
      @reset="resetFilters"
    >
      <template #filters>
        <div class="filter-field">
          <label>状态</label>
          <CustomSelect v-model="filterStatus" :options="statusOptions" style="width: 120px;" />
        </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>状态</th>
              <th>排序</th>
              <th>创建时间</th>
              <th class="text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="column in filteredColumns" :key="column.id" class="group transition-colors duration-200">
              <td class="font-mono text-xs text-white/40">#{{ column.id }}</td>
              <td>
                <div v-if="column.cover" class="w-10 h-10 rounded bg-cover bg-center border border-white/10" :style="{ backgroundImage: `url(${column.cover})` }"></div>
                <div v-else class="w-10 h-10 rounded bg-white/5 border border-white/10 flex items-center justify-center text-xs text-white/30">无</div>
              </td>
              <td class="font-medium text-white group-hover:text-art-accent transition-colors">{{ column.name }}</td>
              <td class="text-sm text-white/70 max-w-xs truncate">{{ column.description || '-' }}</td>
              <td>
                <span :class="['px-2 py-1 rounded-full text-xs font-medium border', column.isActive === 1 ? 'bg-green-500/10 text-green-400 border-green-500/20' : 'bg-gray-500/10 text-gray-400 border-gray-500/20']">
                  {{ column.isActive === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="text-xs text-art-muted">{{ column.sortOrder }}</td>
              <td class="text-art-muted text-xs">{{ column.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/columns/${column.id}/edit`" class="admin-btn-secondary py-1 px-3 text-xs">
                    编辑
                  </router-link>
                  <button @click="handleDelete(column.id)" class="admin-btn-danger py-1 px-3 text-xs">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div v-if="filteredColumns.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/columns/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 { getAdminColumns, deleteColumn, Column } 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 columns = ref<Column[]>([])
const { keyword, appliedKeyword, apply, reset } = useAppliedKeyword()
const filterStatus = ref<number | string>('')
const appliedStatus = ref<number | string>('')

const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 1, label: '启用' },
  { value: 0, label: '禁用' },
]

const filteredColumns = computed(() => columns.value.filter(c => {
  if (!matchKeywordFn(c, appliedKeyword.value, item => `${item.name} ${item.description || ''}`)) return false
  if (appliedStatus.value !== '' && c.isActive !== Number(appliedStatus.value)) return false
  return true
}))

const applyFilter = () => {
  apply()
  appliedStatus.value = filterStatus.value
}

const resetFilters = () => {
  reset()
  filterStatus.value = ''
  appliedStatus.value = ''
}

const fetchColumns = async () => {
  try {
    columns.value = await getAdminColumns()
  } catch (error) {
    console.error('Error fetching columns:', error)
    toast.showToast('获取专栏列表失败', 'error')
  }
}

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

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