<template>
  <div>
    <h1 class="text-2xl font-bold mb-6">评论管理</h1>

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

      <UTable
        :columns="columns"
        :rows="comments"
        :loading="loading"
        hover
      >
        <template #content-data="{ row }">
          <p class="max-w-md truncate">{{ row.content }}</p>
        </template>

        <template #article-data="{ row }">
          <NuxtLink :to="`/article/${row.articleId}`" class="text-indigo-600 dark:text-indigo-400 hover:underline">
            查看文章
          </NuxtLink>
        </template>

        <template #author-data="{ row }">
          {{ row.author?.displayName || row.author?.username || row.authorName || '匿名用户' }}
        </template>

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

        <template #actions-data="{ row }">
          <div class="flex items-center gap-2">
            <UButton
              v-if="row.status === 'pending'"
              variant="ghost"
              size="xs"
              icon="i-heroicons-check"
              color="green"
              @click="approveComment(row)"
            />
            <UButton
              v-if="row.status === 'pending'"
              variant="ghost"
              size="xs"
              icon="i-heroicons-x-mark"
              color="red"
              @click="rejectComment(row)"
            />
            <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>确定要删除这条评论吗？此操作不可撤销。</p>
        <template #footer>
          <div class="flex gap-4">
            <UButton variant="ghost" @click="deleteModalOpen = false">取消</UButton>
            <UButton color="red" @click="deleteComment" :loading="deleting">删除</UButton>
          </div>
        </template>
      </UCard>
    </UModal>
  </div>
</template>

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

const { get, delete: deleteRequest } = useApi()

const comments = 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 articleIdFilter = ref('')

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

const columns = [
  { key: 'content', label: '评论内容' },
  { key: 'article', label: '文章' },
  { key: 'author', label: '作者' },
  { key: 'status', label: '状态' },
  { key: 'createdAt', label: '时间' },
  { key: 'actions', label: '操作' },
]

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已拒绝', value: 'rejected' },
  { label: '可疑', value: 'suspicious' },
]

const statusLabels: Record<string, string> = {
  pending: '待审核',
  approved: '已通过',
  rejected: '已拒绝',
  suspicious: '可疑',
}

const statusColors: Record<string, string> = {
  pending: 'yellow',
  approved: 'green',
  rejected: 'red',
  suspicious: 'orange',
}

const loadComments = async () => {
  loading.value = true
  try {
    const query = new URLSearchParams()
    query.set('page', page.value.toString())
    query.set('limit', limit.toString())
    if (statusFilter.value) query.set('status', statusFilter.value)
    if (articleIdFilter.value) query.set('articleId', articleIdFilter.value)

    const response = await get(`/admin/comments?${query}`)
    comments.value = response.items
    total.value = response.total
    totalPages.value = response.totalPages
  } catch (error) {
    console.error('Failed to load comments:', error)
  } finally {
    loading.value = false
  }
}

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

const approveComment = async (comment: any) => {
  try {
    await useApi().put(`/admin/comments/${comment.id}/status`, { status: 'approved' })
    await loadComments()
  } catch (error) {
    console.error('Failed to approve comment:', error)
  }
}

const rejectComment = async (comment: any) => {
  try {
    await useApi().put(`/admin/comments/${comment.id}/status`, { status: 'rejected' })
    await loadComments()
  } catch (error) {
    console.error('Failed to reject comment:', error)
  }
}

const confirmDelete = (comment: any) => {
  selectedComment.value = comment
  deleteModalOpen.value = true
}

const deleteComment = async () => {
  if (!selectedComment.value) return
  deleting.value = true
  try {
    await deleteRequest(`/admin/comments/${selectedComment.value.id}`)
    deleteModalOpen.value = false
    selectedComment.value = null
    await loadComments()
  } catch (error) {
    console.error('Failed to delete comment:', error)
  } finally {
    deleting.value = false
  }
}

watch([page, statusFilter, articleIdFilter], loadComments)

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