<template>
  <div style="max-width: 1200px">
    <n-space justify="space-between" align="center" style="margin-bottom: 20px">
      <div>
        <h1 style="margin: 0 0 4px; font-size: 20px; font-weight: 600; color: #111827">客户评价</h1>
        <p style="margin: 0; font-size: 13px; color: #9ca3af">管理客户评价 · 对应官网「客户评价」页面</p>
      </div>
      <n-space>
        <n-button tag="a" href="/reviews" target="_blank" secondary>查看前台</n-button>
        <n-button type="primary" @click="navigateTo('/admin/reviews/new')">新增评价</n-button>
      </n-space>
    </n-space>

    <n-card>
      <n-space style="margin-bottom: 16px">
        <n-input v-model:value="search" placeholder="搜索客户、内容..." clearable style="width: 260px" @keyup.enter="page = 1; loadData()">
          <template #prefix><span style="color: #9ca3af">&#128269;</span></template>
        </n-input>
        <n-button @click="page = 1; loadData()">搜索</n-button>
      </n-space>

      <n-data-table :columns="columns" :data="list" :loading="loading" :row-key="(row) => row.id" :pagination="false" size="small" striped />

      <n-space justify="end" style="margin-top: 16px" v-if="totalPages > 1">
        <n-pagination v-model:page="page" :page-count="totalPages" @update:page="loadData" />
      </n-space>
    </n-card>
  </div>
</template>

<script setup>
import { h } from 'vue'
import { NButton, NCard, NSpace, NInput, NDataTable, NTag, NPagination, NPopconfirm, NRate } from 'naive-ui'
import { useMessage } from 'naive-ui'

definePageMeta({ layout: 'admin', middleware: 'admin' })

const { adminFetch } = useAdmin()
const message = useMessage()
const list = ref([])
const total = ref(0)
const page = ref(1)
const totalPages = ref(1)
const loading = ref(false)
const search = ref('')

const columns = [
  { title: 'ID', key: 'id', width: 50, render: (row) => h('span', { style: 'color: #9ca3af; font-size: 12px' }, row.id) },
  {
    title: '客户', key: 'author',
    render: (row) => h('a', {
      style: 'color: #111827; text-decoration: none; font-weight: 500; cursor: pointer',
      onClick: () => navigateTo(`/admin/reviews/${row.id}`),
    }, row.author),
  },
  {
    title: '评分', key: 'rating', width: 120,
    render: (row) => h(NRate, { value: row.rating || 5, readonly: true, size: 'small' }),
  },
  { title: '产品版本', key: 'title', width: 100 },
  {
    title: '内容摘要', key: 'content',
    render: (row) => h('span', { style: 'color: #9ca3af; font-size: 12px' }, row.content?.slice(0, 50)),
  },
  { title: '出行日期', key: 'date', width: 90, render: (row) => h('span', { style: 'color: #9ca3af; font-size: 12px' }, row.date) },
  {
    title: '状态', key: 'published', width: 70,
    render: (row) => h(NTag, {
      size: 'small', type: row.published ? 'success' : 'default', bordered: false,
      style: 'cursor: pointer',
      onClick: () => togglePublish(row),
    }, () => row.published ? '已发布' : '草稿'),
  },
  {
    title: '操作', key: 'actions', width: 120,
    render: (row) => h(NSpace, { size: 'small' }, () => [
      h(NButton, { size: 'tiny', text: true, type: 'primary', onClick: () => navigateTo(`/admin/reviews/${row.id}`) }, () => '编辑'),
      h(NPopconfirm, { onPositiveClick: () => handleDelete(row) }, {
        trigger: () => h(NButton, { size: 'tiny', text: true, type: 'error' }, () => '删除'),
        default: () => `确定删除「${row.author}」的评价？`,
      }),
    ]),
  },
]

async function loadData() {
  loading.value = true
  try {
    const d = await adminFetch(`/api/admin/reviews?page=${page.value}&limit=20&search=${encodeURIComponent(search.value)}`)
    list.value = d.items; total.value = d.total; totalPages.value = d.totalPages
  } catch { message.error('加载失败') } finally { loading.value = false }
}

async function togglePublish(item) {
  try {
    await adminFetch(`/api/admin/reviews/${item.id}`, { method: 'PUT', body: { published: !item.published } })
    item.published = !item.published
  } catch { message.error('操作失败') }
}

async function handleDelete(item) {
  try {
    await adminFetch(`/api/admin/reviews/${item.id}`, { method: 'DELETE' })
    message.success('已删除')
    loadData()
  } catch { message.error('删除失败') }
}

onMounted(loadData)
</script>
