<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { NCard, NTag, NButton, NSkeleton, NEmpty, NInput, useMessage } from 'naive-ui'
import { api } from '../../api/client'

const message = useMessage()

const cancerType = ref('肺癌')
const treatmentLine = ref<string | null>(null)
const loading = ref(false)
const result = ref<any>(null)

const lineColors: Record<string, string> = {
  '1L': '#d03050', '2L': '#f0a020', '3L': '#18a058',
  adjuvant: '#2080f0', neoadjuvant: '#8a2be2', maintenance: '#999',
}
const lineLabels: Record<string, string> = {
  '1L': '一线', '2L': '二线', '3L': '三线',
  adjuvant: '辅助', neoadjuvant: '新辅助', maintenance: '维持',
}
const levelColors: Record<string, string> = {
  '1': '#d03050', '1A': '#d03050', '1B': '#d03050',
  '2A': '#f0a020', '2B': '#e68a00',
  '3': '#18a058',
}

const treatmentsByLine = computed(() => {
  if (!result.value?.standard_treatments) return []
  const groups: Record<string, any[]> = {}
  for (const t of result.value.standard_treatments) {
    const line = t.line || 'other'
    if (!groups[line]) groups[line] = []
    groups[line].push(t)
  }
  const order = ['1L', '2L', '3L', 'adjuvant', 'neoadjuvant', 'maintenance', 'other']
  return order.filter(k => groups[k]).map(k => ({ line: k, items: groups[k] }))
})

async function load() {
  loading.value = true
  result.value = null
  try {
    const params: Record<string, any> = { cancer_type: cancerType.value }
    if (treatmentLine.value) params.treatment_line = treatmentLine.value
    const { data } = await api.get('/approvals/guidelines/quick-index', { params })
    result.value = data
  } catch (e: any) {
    message.error(e?.response?.data?.detail || '加载治疗方案失败')
  } finally {
    loading.value = false
  }
}

onMounted(load)
</script>

<template>
  <div style="max-width:1100px;margin:0 auto;padding:32px 24px">
    <div style="text-align:center;margin-bottom:28px">
      <h1 style="font-size:26px;margin-bottom:6px">💊 治疗方案索引</h1>
      <p style="color:var(--text-secondary);font-size:14px">
        NCCN / CSCO / ESMO 标准方案 · 按癌种 + 治疗线数检索
      </p>
    </div>

    <!-- 筛选栏 -->
    <div style="display:flex;gap:12px;margin-bottom:20px;flex-wrap:wrap;align-items:center">
      <NInput v-model:value="cancerType" placeholder="癌种（肺癌 / NSCLC / Breast...）" style="width:240px" size="small" clearable @keyup.enter="load" />
      <NButton size="small" type="primary" @click="load" class="sky-btn">搜索</NButton>
      <div style="display:flex;gap:4px;flex-wrap:wrap">
        <NButton size="tiny" :type="treatmentLine===null?'primary':'default'"
          @click="treatmentLine=null;load()">全部</NButton>
        <NButton v-for="(label, key) in lineLabels" :key="key" size="tiny"
          :type="treatmentLine===key?'primary':'default'"
          @click="treatmentLine=key;load()">
          <template #icon>
            <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--n-color)"></span>
          </template>
          {{ label }}
        </NButton>
      </div>
    </div>

    <!-- 加载 -->
    <NSkeleton v-if="loading" text :repeat="5" />

    <!-- 空 -->
    <NEmpty v-else-if="!result" description="暂无数据" style="padding:48px 0" />

    <!-- 结果 -->
    <template v-else>
      <div style="margin-bottom:16px;font-size:13px;color:var(--text-secondary)">
        当前癌种：<strong>{{ result.cancer_type }}</strong>
        · 引用指南：<span v-for="(g,i) in result.guidelines_referenced" :key="i">
          {{ g }}{{ i < result.guidelines_referenced.length - 1 ? ' / ' : '' }}
        </span>
        · 共 {{ result.standard_treatments.length }} 条方案
      </div>

      <!-- 按治疗线分组 -->
      <div v-for="group in treatmentsByLine" :key="group.line" style="margin-bottom:20px">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:10px">
          <NTag size="small" :color="{ color: lineColors[group.line] || '#999' }">
            {{ lineLabels[group.line] || group.line }}
          </NTag>
          <span style="font-size:12px;color:var(--text-muted)">{{ (group.items || []).length }} 项方案</span>
        </div>

        <NCard v-for="(t, i) in (group.items || [])" :key="i" size="small" style="margin-bottom:6px">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px">
            <div style="flex:1">
              <div style="font-size:14px;font-weight:500;margin-bottom:4px">
                {{ t.recommendation }}
              </div>
              <div style="font-size:12px;color:var(--text-muted)">
                <NTag size="tiny" style="margin-right:4px"
                  :color="levelColors[t.level] ? { color: levelColors[t.level] } : undefined"
                  :bordered="false">{{ t.level || '—' }}</NTag>
                <span>{{ t.guideline }}</span>
                <span v-if="t.evidence" style="margin-left:6px">· 📄 {{ t.evidence }}</span>
              </div>
            </div>
          </div>
        </NCard>
      </div>
    </template>
  </div>
</template>
