<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {NCard, NTag, NButton, NSkeleton, NGrid, NGridItem, NModal, NPagination, NEmpty, NDrawer, NDrawerContent, useMessage, NIcon} from 'naive-ui'
import { api } from '../../api/client'
import { AddOutline, CheckmarkOutline } from '@vicons/ionicons5'

const message = useMessage()

const guidelines = ref<any[]>([])
const loading = ref(true)
const source = ref<string | null>(null)
const evidence = ref<any[]>([])
const evidenceLoading = ref(false)
const showEvidenceModal = ref(false)
const selectedGuideline = ref<any>(null)
const relatedDrugs = ref<any[]>([])
const relatedDrugsLoading = ref(false)
// ── Drug Detail Drawer ──
const showDrugDrawer = ref(false)
const selectedDrugId = ref<string | null>(null)
const drugLabelData = ref<any>(null)
const drugLabelLoading = ref(false)
const drugRelatedGuidelines = ref<any[]>([])
const drugGuidelinesLoading = ref(false)

async function viewDrugDetail(drugId: string) {
  selectedDrugId.value = drugId
  showDrugDrawer.value = true
  drugLabelLoading.value = true
  drugRelatedGuidelines.value = []
  try {
    const { data } = await api.get(`/approvals/drug-approvals/${drugId}/label`)
    drugLabelData.value = data
  } catch { message.error('加载药品详情失败') }
  finally { drugLabelLoading.value = false }
  drugGuidelinesLoading.value = true
  try {
    const { data } = await api.get(`/approvals/drug-approvals/${drugId}/guidelines`)
    drugRelatedGuidelines.value = data.guidelines || []
  } catch { /* silent */ }
  finally { drugGuidelinesLoading.value = false }
}
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

onMounted(loadData)
async function loadData() {
  loading.value = true
  try {
    const params: any = { page: page.value, page_size: pageSize.value }
    if (source.value) params.source = source.value
    const { data } = await api.get('/approvals/guidelines', { params })
    guidelines.value = data.items || []
    total.value = data.total || 0
  } catch (e: any) { message.error(e?.response?.data?.detail || '加载指南失败') }
  finally { loading.value = false }
}
async function viewEvidence(g: any) {
  selectedGuideline.value = g; showEvidenceModal.value = true; evidenceLoading.value = true; relatedDrugs.value = []; relatedDrugsLoading.value = true
  try { const { data } = await api.get(`/approvals/guidelines/${g.id}/evidence`); evidence.value = data.items || [] }
  catch (e: any) { message.error(e?.response?.data?.detail || '加载证据失败') }
  finally { evidenceLoading.value = false }
  try { const { data } = await api.get(`/approvals/guidelines/${g.id}/drugs`); relatedDrugs.value = data.drugs || [] }
  catch { /* silent */ }
  finally { relatedDrugsLoading.value = false }
}

const sourceNames: Record<string, { name: string; color: string }> = { NCCN:{name:'NCCN',color:'#2080f0'}, CSCO:{name:'CSCO',color:'#d03050'}, ESMO:{name:'ESMO',color:'#18a058'}, NHC:{name:'卫健委',color:'#f0a020'} }
const lineLabels: Record<string,string> = { '1L':'一线', '2L':'二线', '3L':'三线', adjuvant:'辅助', neoadjuvant:'新辅助', maintenance:'维持' }
</script>

<template>
  <div style="max-width:1000px;margin:0 auto;padding:32px 24px">
    <div style="text-align:center;margin-bottom:24px">
      <h1 style="font-size:28px;margin-bottom:4px">📋 临床指南更新</h1>
      <p style="color:var(--text-secondary);font-size:14px">追踪 NCCN/CSCO/ESMO/卫健委 指南 · 推荐方案 → 证据文献链</p>
      <NButton size="small" text type="primary" style="margin-top:4px" @click="$router.push('/guidelines/plans')">
        💊 治疗方案索引 →
      </NButton>
    </div>
    <div style="display:flex;gap:8px;margin-bottom:20px;justify-content:center;flex-wrap:wrap">
      <NButton :type="!source?'primary':'default'" size="small" @click="source=null;loadData()" class="sky-btn"><template #icon><NIcon size="14"><CheckmarkOutline /></NIcon></template>全部</NButton>
      <NButton :type="source==='NCCN'?'primary':'default'" size="small" @click="source='NCCN';loadData()" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>NCCN</NButton>
      <NButton :type="source==='CSCO'?'primary':'default'" size="small" @click="source='CSCO';loadData()" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>CSCO</NButton>
      <NButton :type="source==='ESMO'?'primary':'default'" size="small" @click="source='ESMO';loadData()" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>ESMO</NButton>
      <NButton :type="source==='NHC'?'primary':'default'" size="small" @click="source='NHC';loadData()" class="sky-btn"><template #icon><NIcon size="14"><CheckmarkOutline /></NIcon></template>卫健委</NButton>
    </div>
    <NSkeleton v-if="loading" text :repeat="4" />
    <NEmpty v-else-if="!guidelines.length" description="暂无指南更新" style="padding:48px 0" />
    <n-grid v-else :cols="2" :x-gap="12" responsive="screen" :y-gap="12">
      <n-grid-item v-for="g in guidelines" :key="g.id">
        <n-card size="small">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center">
              <n-tag size="small" :color="{color:sourceNames[g.source]?.color||'#999'}" :bordered="false">{{ sourceNames[g.source]?.name||g.source }}</n-tag>
              <strong>{{ g.version }}</strong>
            </div>
          </template>
          <div style="font-size:12px;color:var(--text-muted);margin-bottom:6px">📅 {{ g.publish_date }}</div>
          <div style="font-size:14px;color:var(--text-secondary);line-height:1.6">{{ g.change_summary_zh || '暂无变更摘要' }}</div>
          <NButton size="small" text type="primary" style="margin-top:6px;font-size:12px" @click="viewEvidence(g)">📚 查看证据文献链 →</NButton>
          <NButton size="small" text style="margin-top:6px;margin-left:12px;font-size:12px" @click="$router.push('/guidelines/compare')">🔄 版本对比 →</NButton>
        </n-card>
      </n-grid-item>
    </n-grid>

    <div v-if="total > pageSize" style="display:flex;justify-content:center;margin-top:24px">
      <NPagination :page="page" :page-size="pageSize" :item-count="total" @update:page="p => { page=p; loadData() }" />
    </div>

    <NModal v-model:show="showEvidenceModal" title="证据文献链" closable>
      <NCard v-if="selectedGuideline" style="width:min(600px,calc(100vw - 48px));max-height:70vh;overflow-y:auto">
        <h4 style="margin-top:0">{{ sourceNames[selectedGuideline.source]?.name }} {{ selectedGuideline.version }}</h4>
        <NSkeleton v-if="evidenceLoading" text :repeat="3" />
        <div v-else-if="!evidence.length" style="color:var(--text-muted);text-align:center;padding:16px">暂无证据文献</div>
        <div v-for="(ev,i) in evidence" :key="i" style="padding:8px 0;border-bottom:1px solid var(--border-color);font-size:14px">
          <div style="display:flex;gap:6px;align-items:flex-start;margin-bottom:4px">
            <NTag size="tiny" type="success">{{ ev.level||'—' }}</NTag>
            <NTag size="tiny" v-if="ev.treatment_line">{{ lineLabels[ev.treatment_line]||ev.treatment_line }}</NTag>
          </div>
          <p style="margin:4px 0;line-height:1.5"><strong>{{ ev.recommendation }}</strong></p>
          <p style="margin:4px 0;font-size:13px;color:var(--text-secondary)">
            📄 <span style="color:#1a5276;cursor:pointer" @click="$router.push(`/literature/${ev.pmid}`)">{{ ev.title }}</span>
            <span style="color:var(--text-muted);margin-left:6px">{{ ev.journal }}</span>
          </p>
        </div>

        <!-- 相关药品 -->
        <div v-if="relatedDrugs.length" style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-color)">
          <h4 style="margin:0 0 8px;font-size:13px">💊 相关药品</h4>
          <div style="display:flex;flex-wrap:wrap;gap:6px">
            <NTag v-for="d in relatedDrugs.slice(0, 10)" :key="d.id"
              size="small" :bordered="false"
              style="cursor:pointer" @click="viewDrugDetail(d.id)">
              {{ d.drug_name }}<span style="opacity:0.6;margin-left:4px">{{ d.target }}</span>
            </NTag>
          </div>
        </div>
      </NCard>
    </NModal>
  </div>

  <!-- Drug Detail Drawer -->
  <NDrawer v-model:show="showDrugDrawer" :width="600" placement="right">
    <NDrawerContent title="💊 药品详情" closable>
      <NSkeleton v-if="drugLabelLoading" text :repeat="6" />
      <template v-else-if="drugLabelData">
        <div style="margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid var(--border-color)">
          <div style="font-size:16px;font-weight:700">{{ drugLabelData.approval?.drug_name }}</div>
          <div style="font-size:13px;color:var(--text-secondary);margin-top:4px">
            {{ drugLabelData.approval?.generic_name }}
            <NTag v-if="drugLabelData.approval?.target" size="tiny" style="margin-left:6px" :bordered="false">{{ drugLabelData.approval.target }}</NTag>
          </div>
          <div style="font-size:13px;color:var(--text-secondary);margin-top:4px">
            {{ drugLabelData.approval?.indication }}
          </div>
        </div>

        <!-- FDA Label -->
        <template v-if="drugLabelData.labels?.length">
          <div v-for="(l, li) in drugLabelData.labels" :key="l.set_id" style="margin-bottom:16px">
            <NTag size="tiny" style="margin-bottom:6px" :bordered="false">标签 v{{ drugLabelData.labels.length - li }} · {{ l.effective_time?.slice(0,4) || '?' }}</NTag>
            <div v-if="l.mechanism_of_action" style="margin-bottom:8px">
              <div style="font-size:13px;font-weight:700;margin-bottom:4px">作用机制</div>
              <div style="font-size:13px;color:var(--text-secondary);line-height:1.6;white-space:pre-wrap;max-height:120px;overflow-y:auto">{{ l.mechanism_of_action }}</div>
            </div>
            <div v-if="l.indications_and_usage" style="margin-bottom:8px">
              <div style="font-size:13px;font-weight:700;margin-bottom:4px">适应症及用法</div>
              <div style="font-size:13px;color:var(--text-secondary);line-height:1.6;white-space:pre-wrap;max-height:200px;overflow-y:auto">{{ l.indications_and_usage }}</div>
            </div>
          </div>
        </template>
        <NEmpty v-else description="暂无 FDA 标签数据" style="padding:8px 0" />

        <!-- Related Guidelines -->
        <div style="margin-top:16px;border-top:1px solid var(--border-color);padding-top:12px">
          <div style="font-size:14px;font-weight:700;margin-bottom:8px">📋 指南推荐</div>
          <NSkeleton v-if="drugGuidelinesLoading" text :repeat="2" />
          <div v-else-if="!drugRelatedGuidelines.length" style="font-size:13px;color:var(--text-muted)">暂无关联指南</div>
          <div v-for="g in drugRelatedGuidelines" :key="g.id"
            style="padding:8px 10px;background:var(--bg-hover);border-radius:6px;margin-bottom:6px;cursor:pointer"
            @click="viewEvidence(g)">
            <div style="display:flex;gap:6px;align-items:center;margin-bottom:4px">
              <NTag size="tiny" :bordered="false" :color="{
                color: ({ NCCN:'#2080f0',CSCO:'#d03050',ESMO:'#18a058',NHC:'#f0a020' } as Record<string,string>)[g.source] || '#999'
              }">{{ g.source }}</NTag>
              <strong style="font-size:13px">{{ g.version }}</strong>
              <span style="font-size:11px;color:var(--text-muted);margin-left:auto">{{ g.publish_date }}</span>
            </div>
            <div style="font-size:12px;color:var(--text-secondary);line-height:1.4">{{ g.change_summary_zh?.slice(0, 80) }}{{ g.change_summary_zh?.length > 80 ? '…' : '' }}</div>
          </div>
        </div>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
