<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { toBeijingDate } from '../../utils/date'
import { AddOutline } from '@vicons/ionicons5'
import { useRouter } from 'vue-router'
import { NButton, NCard, NDataTable, NEmpty, NIcon, NInput, NModal, NSpace, NTag, useMessage } from 'naive-ui'
import { api } from '../../api/client'
import type { SystematicReview } from '../../types'

const router = useRouter()
const message = useMessage()

const reviews = ref<SystematicReview[]>([])
const loading = ref(false)
const showCreate = ref(false)
const newTitle = ref('')
const newObjective = ref('')
const creating = ref(false)

async function loadReviews() {
  loading.value = true
  try {
    const res = await api.get('/reviews')
    reviews.value = res.data.items || []
  } catch (e) {
    message.error('加载系统评价列表失败')
  } finally {
    loading.value = false
  }
}

async function createReview() {
  if (!newTitle.value.trim()) return
  creating.value = true
  try {
    const res = await api.post('/reviews', { title: newTitle.value.trim(), objective: newObjective.value.trim() || null })
    showCreate.value = false
    newTitle.value = ''
    newObjective.value = ''
    message.success('创建成功')
    router.push(`/app/reviews/${res.data.id}`)
  } catch (e) {
    message.error('创建失败')
  } finally {
    creating.value = false
  }
}

const statusMap: Record<string, { label: string; type: 'info' | 'success' | 'warning' | 'default' | 'error' }> = {
  draft: { label: '草稿', type: 'default' },
  active: { label: '进行中', type: 'info' },
  completed: { label: '已完成', type: 'success' },
  archived: { label: '已归档', type: 'warning' },
}

const columns = [
  { title: '标题', key: 'title', ellipsis: { tooltip: true } },
  { title: '状态', key: 'status', width: 100,
    render: (row: SystematicReview) => {
      const s = statusMap[row.status] || { label: row.status, type: 'default' }
      return h(NTag, { type: s.type, size: 'small' }, { default: () => s.label })
    }
  },
  { title: 'PRISMA 阶段', key: 'prisma_stage', width: 130 },
  { title: '创建时间', key: 'created_at', width: 180,
    render: (row: SystematicReview) => toBeijingDate(row.created_at) },
  { title: '操作', key: 'actions', width: 100,
    render: (row: SystematicReview) => h(NButton, { size: 'small', type: 'primary', ghost: true, onClick: () => router.push(`/app/reviews/${row.id}`) }, { default: () => '详情' }) },
]
const scrollX = 810

onMounted(loadReviews)
</script>

<template>
  <div class="reviews-page">
    <div class="page-header">
      <h2>系统评价 / Meta 分析</h2>
      <NButton type="primary" @click="showCreate = true" class="sky-btn">
        <template #icon><NIcon size="14"><AddOutline /></NIcon></template>
        新建项目
      </NButton>
    </div>

    <NCard>
      <NDataTable
        :columns="columns"
        :data="reviews"
        :loading="loading"
        :scroll-x="scrollX"
        :bordered="false"
        :row-key="(r: SystematicReview) => r.id"
        :empty="h(NEmpty, { description: '暂无系统评价项目' })"
      />
    </NCard>

    <!-- 新建对话框 -->
    <NModal v-model:show="showCreate" title="新建系统评价" preset="card" style="width: 500px">
      <NSpace vertical>
        <NInput v-model:value="newTitle" placeholder="项目标题（必填）" />
        <NInput v-model:value="newObjective" type="textarea" rows="3" placeholder="研究目的（可选）" />
        <NButton type="primary" :loading="creating" :disabled="!newTitle.trim()" @click="createReview" class="sky-btn">
          <template #icon><NIcon size="14"><AddOutline /></NIcon></template>
          创建
        </NButton>
      </NSpace>
    </NModal>
  </div>
</template>

<style scoped>
.reviews-page { padding: 24px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.page-header h2 { margin: 0; }
</style>
