<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-bold">文章管理</h1>
      <UButton to="/create" color="indigo" icon="i-heroicons-plus">
        新建文章
      </UButton>
    </div>

    <UCard>
      <div class="flex gap-4 mb-4">
        <USelect
          v-model="statusFilter"
          :options="statusOptions"
          class="w-40"
        />
        <USelect
          v-model="visibilityFilter"
          :options="visibilityOptions"
          class="w-40"
        />
        <UButton
          variant="ghost"
          icon="i-heroicons-arrow-path"
          @click="refresh"
          :loading="loading"
        >
          刷新
        </UButton>
      </div>

      <UTable
        :columns="columns"
        :rows="articles"
        :loading="loading"
        hover
      >
        <template #title-data="{ row }">
          <div class="flex items-center gap-3">
            <img
              v-if="row.coverImageUrl"
              :src="row.coverImageUrl"
              class="w-10 h-10 object-cover rounded"
            />
            <div class="w-10 h-10 bg-gray-200 rounded flex items-center justify-center" v-else>
              <UIcon name="i-heroicons-image" class="w-5 h-5 text-gray-400" />
            </div>
            <NuxtLink :to="`/article/${row.slug}`" class="text-indigo-600 dark:text-indigo-400 hover:underline font-medium">
              {{ row.title }}
            </NuxtLink>
          </div>
        </template>

        <template #author-data="{ row }">
          {{ row.author.displayName || row.author.username }}
        </template>

        <template #status-data="{ row }">
          <UBadge
            :label="statusLabels[row.status]"
            :color="statusColors[row.status]"
            size="xs"
          />
        </template>

        <template #visibility-data="{ row }">
          <UIcon :name="visibilityIcons[row.visibility]" class="w-5 h-5" />
        </template>

        <template #actions-data="{ row }">
          <div class="flex items-center gap-2">
            <UButton
              variant="ghost"
              size="xs"
              icon="i-heroicons-pencil"
              :to="`/article/${row.id}/edit`"
            />
            <UButton
              variant="ghost"
              size="xs"
              icon="i-heroicons-trash"
              color="red"
              @click="confirmDelete(row)"
            />
          </div>
        </template>
      </UTable>

      <div v-if="totalPages > 1" class="mt-4 flex justify-center">
        <UPagination
          v-model="page"
          :total="total"
          :page-size="limit"
        />
      </div>
    </UCard>

    <UModal v-model="deleteModalOpen">
      <UCard>
        <template #header>
          <h3 class="text-lg font-semibold">确认删除</h3>
        </template>
        <p>确定要删除文章 "{{ selectedArticle?.title }}" 吗？此操作不可撤销。</p>
        <template #footer>
          <div class="flex gap-4">
            <UButton variant="ghost" @click="deleteModalOpen = false">取消</UButton>
            <UButton color="red" @click="deleteArticle" :loading="deleting">删除</UButton>
          </div>
        </template>
      </UCard>
    </UModal>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'admin',
  middleware: ['admin'],
})

const { fetchArticles } = useArticles()
const { delete: deleteRequest } = useApi()

const articles = ref<any[]>([])
const loading = ref(true)
const page = ref(1)
const limit = 20
const total = ref(0)
const totalPages = ref(0)

const statusFilter = ref('')
const visibilityFilter = ref('')

const deleteModalOpen = ref(false)
const selectedArticle = ref<any>(null)
const deleting = ref(false)

const columns = [
  { key: 'title', label: '标题' },
  { key: 'author', label: '作者' },
  { key: 'status', label: '状态' },
  { key: 'visibility', label: '可见性' },
  { key: 'viewCount', label: '查看数' },
  { key: 'publishedAt', label: '发布时间' },
  { key: 'actions', label: '操作' },
]

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '归档', value: 'archived' },
]

const visibilityOptions = [
  { label: '全部可见性', value: '' },
  { label: '公开', value: 'public' },
  { label: '未列出', value: 'unlisted' },
  { label: '私密', value: 'private' },
]

const statusLabels: Record<string, string> = {
  draft: '草稿',
  published: '已发布',
  archived: '归档',
}

const statusColors: Record<string, string> = {
  draft: 'yellow',
  published: 'green',
  archived: 'gray',
}

const visibilityIcons: Record<string, string> = {
  public: 'i-heroicons-globe',
  unlisted: 'i-heroicons-link',
  private: 'i-heroicons-lock-closed',
}

const loadArticles = async () => {
  loading.value = true
  try {
    const response = await fetchArticles({
      page: page.value,
      limit,
      status: statusFilter.value,
      visibility: visibilityFilter.value,
    })
    articles.value = response.items
    total.value = response.total
    totalPages.value = response.totalPages
  } catch (error) {
    console.error('Failed to load articles:', error)
  } finally {
    loading.value = false
  }
}

const refresh = () => {
  loadArticles()
}

const confirmDelete = (article: any) => {
  selectedArticle.value = article
  deleteModalOpen.value = true
}

const deleteArticle = async () => {
  if (!selectedArticle.value) return
  deleting.value = true
  try {
    await deleteRequest(`/articles/${selectedArticle.value.id}`)
    deleteModalOpen.value = false
    selectedArticle.value = null
    await loadArticles()
  } catch (error) {
    console.error('Failed to delete article:', error)
  } finally {
    deleting.value = false
  }
}

watch([page, statusFilter, visibilityFilter], loadArticles)

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