<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { h } from 'vue'
import { NCard, NTag, NButton, NSkeleton, NEmpty, NModal, NInput, NSelect, NAlert, NDataTable, useMessage, useDialog, NIcon } from 'naive-ui'
import { AlertCircleOutline, AddOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'

const message = useMessage()
const dialog = useDialog()

const loading = ref(true)
const guidelines = ref<any[]>([])
const updateCheck = ref<any>(null)
const updateCheckLoading = ref(false)

// Create guideline modal
const showCreateModal = ref(false)
const createForm = ref({
  source: '',
  cancer_type: '',
  version: '',
  publish_date: '',
  change_summary_zh: '',
  source_url: '',
})
const creating = ref(false)

// Evidence management
const selectedGid = ref<string | null>(null)
const evidence = ref<any[]>([])
const evLoading = ref(false)
const showEv = ref(false)

const showAddEv = ref(false)
const editingEv = ref<any>(null)
const evForm = ref({ recommendation: '', level: '', treatment_line: null, literature_id: '' })

// ==================== 来源提示信息 ====================
const SOURCE_GUIDE: Record<string, { name_cn: string; color: string; hint: string }> = {
  CSCO: { name_cn: 'CSCO', color: '#d03050', hint: 'CSCO 每年 3-5 月发布新版本。关注 csco.org.cn → 学术专栏 → 指南，或 "CSCO 诊疗指南" 微信公众号。每年 4 月左右会进行年度更新。' },
  NHC: { name_cn: '卫健委', color: '#f0a020', hint: '卫健委每年 1 月左右发布新版《XX 诊疗指南（XXXX 年版）》。关注 nhc.gov.cn → 通知公告，或 "国家卫生健康委员会" 官网 → 医政医管。已发布的 PDF 可在官网搜索下载。' },
  NCCN: { name_cn: 'NCCN', color: '#2080f0', hint: 'PubMed 自动捕获，无需手动维护。' },
  ESMO: { name_cn: 'ESMO', color: '#18a058', hint: 'PubMed 自动捕获，无需手动维护。' },
  ASTRO: { name_cn: 'ASTRO', color: '#7c3aed', hint: 'PubMed 自动捕获，无需手动维护。' },
}

const staleSources = computed(() => {
  if (!updateCheck.value?.sources) return []
  return Object.entries(updateCheck.value.sources)
    .filter(([_, s]: any) => s.status === 'stale')
    .map(([src, s]: any) => ({ source: src, ...s, ...SOURCE_GUIDE[src] }))
})

const treatmentLineOptions = [
  { label: '一线 (1L)', value: '1L' },
  { label: '二线 (2L)', value: '2L' },
  { label: '三线 (3L)', value: '3L' },
  { label: '辅助 (adjuvant)', value: 'adjuvant' },
  { label: '新辅助 (neoadjuvant)', value: 'neoadjuvant' },
  { label: '维持 (maintenance)', value: 'maintenance' },
]

onMounted(async () => {
  await Promise.all([loadGuidelines(), checkUpdates()])
})

async function loadGuidelines() {
  loading.value = true
  try {
    const { data } = await api.get('/admin/guidelines')
    guidelines.value = data.items || []
  } catch (e: any) { message.error(e?.response?.data?.detail || '加载失败') }
  finally { loading.value = false }
}

async function checkUpdates() {
  updateCheckLoading.value = true
  try {
    const { data } = await api.get('/admin/guidelines/check-updates')
    updateCheck.value = data
  } catch (e: any) { /* silent */ }
  finally { updateCheckLoading.value = false }
}

// ==================== 新建指南版本 ====================
function openCreate(src?: string) {
  createForm.value = { source: src || '', cancer_type: '', version: '', publish_date: '', change_summary_zh: '', source_url: '' }
  showCreateModal.value = true
}

async function createGuideline() {
  if (!createForm.value.source || !createForm.value.cancer_type || !createForm.value.version || !createForm.value.publish_date) {
    message.warning('请填写来源、癌种、版本号和发布日期')
    return
  }
  creating.value = true
  try {
    await api.post('/admin/guidelines', createForm.value)
    message.success('指南版本已创建')
    showCreateModal.value = false
    await loadGuidelines()
    await checkUpdates()
  } catch (e: any) { message.error(e?.response?.data?.detail || '创建失败') }
  finally { creating.value = false }
}

// ==================== 证据管理 ====================
async function loadEvidence(gid: string) {
  selectedGid.value = gid
  evLoading.value = true
  showEv.value = true
  try {
    const { data } = await api.get(`/admin/guidelines/${gid}/evidence`)
    evidence.value = data.items || []
  } catch (e: any) { message.error(e?.response?.data?.detail || '加载证据失败') }
  finally { evLoading.value = false }
}

function openAddEv() {
  editingEv.value = null
  evForm.value = { recommendation: '', level: '', treatment_line: null, literature_id: '' }
  showAddEv.value = true
}

function openEditEv(ev: any) {
  editingEv.value = ev
  evForm.value = {
    recommendation: ev.recommendation || '',
    level: ev.level || '',
    treatment_line: ev.treatment_line || null,
    literature_id: ev.literature_id || '',
  }
  showAddEv.value = true
}

async function saveEv() {
  if (!selectedGid.value) return
  const body: Record<string, any> = {
    recommendation: evForm.value.recommendation,
    recommendation_level: evForm.value.level,
    treatment_line: evForm.value.treatment_line,
  }
  try {
    if (editingEv.value) {
      await api.put(`/admin/evidence/${editingEv.value.id}`, body)
      message.success('已更新')
    } else {
      body.literature_id = evForm.value.literature_id
      await api.post(`/admin/guidelines/${selectedGid.value}/evidence`, body)
      message.success('已添加')
    }
    showAddEv.value = false
    await loadEvidence(selectedGid.value)
  } catch (e: any) { message.error(e?.response?.data?.detail || '保存失败') }
}

function confirmDelEv(ev: any) {
  dialog.warning({
    title: '确认删除',
    content: `删除该证据？${ev.recommendation ? '（' + ev.recommendation.slice(0, 40) + '...）' : ''}`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await api.delete(`/admin/evidence/${ev.id}`)
        message.success('已删除')
        await loadEvidence(selectedGid.value!)
      } catch (e: any) { message.error(e?.response?.data?.detail || '删除失败') }
    },
  })
}

const sourceFilter = ref('')

const filteredGuidelines = computed(() => {
  if (!sourceFilter.value) return guidelines.value
  return guidelines.value.filter(g => g.source === sourceFilter.value)
})

const columns = [
  { title: '来源', key: 'source', width: 70 },
  { title: '版本', key: 'version', width: 90 },
  { title: '癌种', key: 'cancer_type', width: 100 },
  { title: '日期', key: 'publish_date', width: 100 },
  { title: '证据数', key: 'evidence_count', width: 70 },
  {
    title: '操作', key: 'actions', width: 130,
    render: (row: any) => h(NButton, { size: 'tiny', type: 'primary', onClick: () => loadEvidence(row.id) }, { default: () => '📚 管理证据' }),
  },
]
const scrollX = 560
</script>

<template>
  <div>
    <h2 style="margin-bottom:16px">📋 指南管理</h2>

    <!-- 更新状态提示 -->
    <div v-if="updateCheckLoading" style="margin-bottom:12px">
      <NSkeleton text :repeat="1" style="max-width:400px" />
    </div>
    <NAlert v-else-if="staleSources.length" type="warning" :bordered="false" closable style="margin-bottom:16px">
      <template #header>
        <NIcon size="18" style="vertical-align:-3px;margin-right:4px"><AlertCircleOutline /></NIcon>
        以下指南可能已有新版本
      </template>
      <div v-for="s in staleSources" :key="s.source" style="margin:4px 0;font-size:13px">
        <strong :style="{color:s.color}">{{ s.name_cn }}</strong>：
        最近版本 {{ s.latest_date }}（共 {{ s.total }} 条），{{ s.hint }}
      </div>
    </NAlert>

    <!-- 工具栏 -->
    <div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;align-items:center">
      <NButton size="small" :type="!sourceFilter?'primary':'default'" @click="sourceFilter=''">全部</NButton>
      <NButton size="small" :type="sourceFilter==='NCCN'?'primary':'default'" @click="sourceFilter='NCCN'">NCCN</NButton>
      <NButton size="small" :type="sourceFilter==='CSCO'?'primary':'default'" @click="sourceFilter='CSCO'" :color="sourceFilter==='CSCO'?'#d03050':undefined">CSCO</NButton>
      <NButton size="small" :type="sourceFilter==='NHC'?'primary':'default'" @click="sourceFilter='NHC'" :color="sourceFilter==='NHC'?'#f0a020':undefined">卫健委</NButton>
      <NButton size="small" :type="sourceFilter==='ESMO'?'primary':'default'" @click="sourceFilter='ESMO'">ESMO</NButton>
      <NButton size="small" :type="sourceFilter==='ASTRO'?'primary':'default'" @click="sourceFilter='ASTRO'">ASTRO</NButton>
      <div style="flex:1" />
      <NButton size="small" type="primary" @click="openCreate()">
        <template #icon><NIcon size="14"><AddOutline /></NIcon></template>
        新建指南版本
      </NButton>
      <NButton size="small" @click="checkUpdates()">刷新状态</NButton>
    </div>

    <!-- 数据表格 -->
    <NSkeleton v-if="loading" text :repeat="6" />
    <NDataTable v-else :columns="columns" :data="filteredGuidelines" :bordered="false" size="small"
      :scroll-x="scrollX"
      :row-props="() => ({ style: 'cursor:pointer' })"
    />

    <!-- ==================== 新建指南版本 Modal ==================== -->
    <NModal v-model:show="showCreateModal" title="新建指南版本" :mask-closable="false">
      <NCard style="width:520px" size="small">
        <div style="display:flex;flex-direction:column;gap:12px">
          <!-- 来源 -->
          <div>
            <label style="font-size:12px;color:var(--text-muted)">来源 *</label>
            <NSelect v-model:value="createForm.source" :options="[
              { label:'CSCO', value:'CSCO' },
              { label:'卫健委 (NHC)', value:'NHC' },
            ]" placeholder="选择来源" />
          </div>

          <!-- 癌种 -->
          <div>
            <label style="font-size:12px;color:var(--text-muted)">癌种（英文）*</label>
            <NInput v-model:value="createForm.cancer_type" placeholder="Lung Cancer / Breast Cancer / Gastric Cancer …" />
          </div>

          <!-- 版本 + 日期 -->
          <div style="display:flex;gap:12px">
            <div style="flex:1">
              <label style="font-size:12px;color:var(--text-muted)">版本号 *</label>
              <NInput v-model:value="createForm.version" placeholder="2025" />
            </div>
            <div style="flex:1">
              <label style="font-size:12px;color:var(--text-muted)">发布日期 *</label>
              <NInput v-model:value="createForm.publish_date" placeholder="2025-04-01" />
            </div>
          </div>

          <!-- 变更摘要 -->
          <div>
            <label style="font-size:12px;color:var(--text-muted)">变更摘要（选填）</label>
            <NInput v-model:value="createForm.change_summary_zh" type="textarea" rows="2" placeholder="驱动基因阴性NSCLC一线免疫治疗推荐更新；…" />
          </div>

          <!-- 来源链接 -->
          <div>
            <label style="font-size:12px;color:var(--text-muted)">官方链接（选填）</label>
            <NInput v-model:value="createForm.source_url" placeholder="https://…" />
          </div>

          <!-- 维护提示 -->
          <NAlert v-if="createForm.source && SOURCE_GUIDE[createForm.source]" type="info" :bordered="false" style="font-size:12px">
            <template #header>📌 {{ SOURCE_GUIDE[createForm.source]?.name_cn }} 维护提示</template>
            {{ SOURCE_GUIDE[createForm.source]?.hint }}
          </NAlert>

          <!-- 按钮 -->
          <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:4px">
            <NButton size="small" @click="showCreateModal=false">取消</NButton>
            <NButton size="small" type="primary" :loading="creating" @click="createGuideline">创建</NButton>
          </div>
        </div>
      </NCard>
    </NModal>

    <!-- ==================== 证据管理 Modal ==================== -->
    <NModal v-model:show="showEv" title="证据管理">
      <NCard style="width:700px;max-height:80vh;overflow-y:auto">
        <template #header>
          <div style="display:flex;justify-content:space-between;align-items:center">
            <span>证据列表</span>
            <NButton size="tiny" type="primary" @click="openAddEv">＋ 添加</NButton>
          </div>
        </template>
        <NSkeleton v-if="evLoading" text :repeat="4" />
        <NEmpty v-else-if="!evidence.length" description="暂无证据" />
        <div v-for="ev in evidence" :key="ev.id"
          style="padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
          <div style="display:flex;gap:6px;align-items:flex-start;margin-bottom:4px">
            <NTag size="tiny" type="success">{{ ev.level || '—' }}</NTag>
            <NTag v-if="ev.treatment_line" size="tiny" :color="{
              color: ({ '1L':'#d03050','2L':'#f0a020','3L':'#18a058',adjuvant:'#2080f0',neoadjuvant:'#8a2be2',maintenance:'#999' } as Record<string,string>)[ev.treatment_line] || '#999'
            }">{{ ev.treatment_line }}</NTag>
          </div>
          <p style="margin:4px 0;line-height:1.5">{{ ev.recommendation }}</p>
          <p style="margin:4px 0;font-size:12px;color:var(--text-muted)">
            PMID {{ ev.pmid }} · {{ ev.journal }}
          </p>
          <div style="display:flex;gap:6px;margin-top:4px">
            <NButton size="tiny" @click="openEditEv(ev)">编辑</NButton>
            <NButton size="tiny" type="error" @click="confirmDelEv(ev)">删除</NButton>
          </div>
        </div>
      </NCard>
    </NModal>

    <!-- 添加/编辑证据 Modal -->
    <NModal v-model:show="showAddEv" title="编辑证据">
      <NCard style="width:500px">
        <div style="display:flex;flex-direction:column;gap:12px">
          <div>
            <label style="font-size:12px;color:var(--text-muted)">推荐方案</label>
            <NInput v-model:value="evForm.recommendation" type="textarea" rows="2" placeholder="Osimertinib+化疗..." />
          </div>
          <div style="display:flex;gap:12px">
            <div style="flex:1">
              <label style="font-size:12px;color:var(--text-muted)">推荐级别</label>
              <NInput v-model:value="evForm.level" placeholder="1A" />
            </div>
            <div style="flex:1">
              <label style="font-size:12px;color:var(--text-muted)">治疗线数</label>
              <NSelect v-model:value="evForm.treatment_line" :options="treatmentLineOptions" placeholder="选择" clearable />
            </div>
          </div>
          <div v-if="!editingEv">
            <label style="font-size:12px;color:var(--text-muted)">文献 ID (UUID)</label>
            <NInput v-model:value="evForm.literature_id" placeholder="literature UUID" />
          </div>
          <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:8px">
            <NButton size="small" @click="showAddEv=false">取消</NButton>
            <NButton size="small" type="primary" @click="saveEv">保存</NButton>
          </div>
        </div>
      </NCard>
    </NModal>
  </div>
</template>
