<script setup lang="ts">
import { toBeijingDate } from '../../utils/date'
import { ref, onMounted } from 'vue'
import { NAlert, NButton, NCard, NDivider, NDrawer, NDrawerContent, NEmpty, NForm, NFormItem, NIcon, NInput, NModal, NPopconfirm, NSkeleton, NTag, type FormRules } from 'naive-ui'
import { AddOutline, CheckmarkCircleOutline, DocumentTextOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const toast = useToast()
const loading = ref(true)
const cases = ref<any[]>([])
const total = ref(0)

// ── New case form ──
const saving = ref(false)
const showNew = ref(false)
const form = ref({ title: '', patient_summary: '', cancer_type: '' })
const formRef = ref()
const formRules: FormRules = {
  title: { required: true, message: '请输入病例标题', trigger: 'blur' },
}

// ── Decide modal ──
const showDecide = ref(false)
const decideCaseId = ref('')
const decisionForm = ref({ conclusion: '', participants: '', meeting_date: '' })
const decideSaving = ref(false)

// ── Detail drawer ──
const selectedCase = ref<any>(null)
const showDetail = ref(false)
const evidenceItems = ref<any[]>([])
const evidenceLoading = ref(false)
const addPmid = ref('')
const addNote = ref('')
const showAddEvidence = ref(false)

// ── Literature pack ──
const showLitPack = ref(false)
const litPackItems = ref<any[]>([])
const litPackLoading = ref(false)
const litPackTerms = ref<string[]>([])
const addingPackPmids = ref<Set<number>>(new Set())

onMounted(loadCases)

function getRoleTagType(role: string): 'info' | 'error' | 'warning' | 'success' | 'default' | 'primary' {
  const map: Record<string, 'info' | 'error' | 'warning' | 'success' | 'default' | 'primary'> = {
    内科: 'info', 外科: 'error', 放疗: 'warning',
    影像: 'success', 病理: 'default', 介入: 'primary',
    护理: 'info', 临床药学: 'warning',
  }
  return map[role] || 'default'
}

async function loadCases() {
  loading.value = true
  try {
    const { data } = await api.get('/mdt/cases', { params: { page: 1, page_size: 50 } })
    cases.value = data.items || []
    total.value = data.total || 0
  } catch (e) {
    toast.apiError(e, '加载 MDT 病例失败')
  } finally {
    loading.value = false
  }
}

async function createCase() {
  try { await formRef.value?.validate() } catch { return }
  saving.value = true
  try {
    await api.post('/mdt/cases', form.value)
    showNew.value = false
    form.value = { title: '', patient_summary: '', cancer_type: '' }
    toast.success('病例创建成功')
    await loadCases()
  } catch (e) {
    toast.apiError(e, '创建病例失败')
  } finally { saving.value = false }
}

function openDecide(c: any) {
  decideCaseId.value = c.id
  decisionForm.value = { conclusion: '', participants: '', meeting_date: '' }
  showDecide.value = true
}

async function submitDecision() {
  decideSaving.value = true
  const parts = decisionForm.value.participants
    .split(/[,，、\s]+/)
    .map((s: string) => s.trim())
    .filter(Boolean)
  try {
    await api.post(`/mdt/cases/${decideCaseId.value}/decide`, {
      conclusion: decisionForm.value.conclusion,
      participants: parts,
      meeting_date: decisionForm.value.meeting_date || null,
    })
    showDecide.value = false
    toast.success('决策已记录')
    await loadCases()
  } catch (e) {
    toast.apiError(e, '记录决策失败')
  } finally { decideSaving.value = false }
}

async function openDetail(c: any) {
  selectedCase.value = c
  showDetail.value = true
  await loadEvidence(c.id)
}

async function loadEvidence(caseId: string) {
  evidenceLoading.value = true
  try {
    const { data } = await api.get(`/mdt/cases/${caseId}/evidence`)
    evidenceItems.value = data.items || []
  } catch (e) {
    toast.apiError(e, '加载证据失败')
  } finally {
    evidenceLoading.value = false
  }
}

async function addEvidence() {
  if (!addPmid.value || !selectedCase.value) return
  const pmids = addPmid.value.split(/[,，\s]+/).map((s: string) => Number(s.trim())).filter((n: number) => n > 0)
  if (!pmids.length) return
  try {
    for (const pmid of pmids) {
      await api.post(`/mdt/cases/${selectedCase.value.id}/evidence`, {
        pmid,
        relevance_note: addNote.value || null,
      })
    }
    addPmid.value = ''
    addNote.value = ''
    showAddEvidence.value = false
    toast.success('证据已添加')
    await loadEvidence(selectedCase.value.id)
  } catch (e) {
    toast.apiError(e, '添加证据失败')
  }
}

async function deleteEvidence(eid: string) {
  if (!selectedCase.value) return
  try {
    await api.delete(`/mdt/cases/${selectedCase.value.id}/evidence/${eid}`)
    toast.success('已删除')
    await loadEvidence(selectedCase.value.id)
  } catch (e) {
    toast.apiError(e, '删除失败')
  }
}

// ── Literature pack ──
async function loadLiteraturePack() {
  if (!selectedCase.value) return
  litPackLoading.value = true
  try {
    const { data } = await api.get(`/mdt/cases/${selectedCase.value.id}/literature-pack`)
    litPackItems.value = data.items || []
    litPackTerms.value = data.terms || []
    showLitPack.value = true
  } catch (e) {
    toast.apiError(e, '加载文献包失败')
  } finally {
    litPackLoading.value = false
  }
}

async function addPackLiterature(pmid: number) {
  if (!selectedCase.value) return
  addingPackPmids.value = new Set([...addingPackPmids.value, pmid])
  try {
    await api.post(`/mdt/cases/${selectedCase.value.id}/evidence`, {
      pmid,
      relevance_note: '文献包推荐',
    })
    toast.success(`PMID ${pmid} 已添加为证据`)
    litPackItems.value = litPackItems.value.filter(i => i.pmid !== pmid)
    await loadEvidence(selectedCase.value.id)
  } catch (e) {
    toast.apiError(e, '添加失败')
  } finally {
    const s = new Set(addingPackPmids.value)
    s.delete(pmid)
    addingPackPmids.value = s
  }
}

async function addAllPack() {
  if (!selectedCase.value || !litPackItems.value.length) return
  const pmids = litPackItems.value.map(i => i.pmid)
  addingPackPmids.value = new Set(pmids)
  let added = 0
  try {
    for (const pmid of pmids) {
      try {
        await api.post(`/mdt/cases/${selectedCase.value.id}/evidence`, {
          pmid, relevance_note: '文献包推荐',
        })
        added++
      } catch { /* skip individual failures */ }
    }
    toast.success(`已添加 ${added} 篇文献到证据`)
    litPackItems.value = []
    await loadEvidence(selectedCase.value.id)
  } finally {
    addingPackPmids.value = new Set()
  }
}
</script>

<template>
  <div class="mdt-container">
    <!-- Header -->
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
      <div>
        <h2 style="margin:0">MDT 多学科协作</h2>
        <p style="margin:4px 0 0;font-size:13px;color:var(--text-muted)">匿名化病例卡 · 文献证据收集 · 决策记录</p>
      </div>
      <NButton type="primary" @click="showNew = true" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>新建病例</NButton>
    </div>

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

    <!-- Empty -->
    <NEmpty v-else-if="!cases.length" description="暂无 MDT 病例" style="padding:48px 0" />

    <!-- Case list -->
    <div v-else style="display:flex;flex-direction:column;gap:12px">
      <NCard v-for="c in cases" :key="c.id" size="small" hoverable @click="openDetail(c)">
        <template #header>
          <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:6px">
            <span><strong>{{ c.title }}</strong></span>
            <NTag size="tiny" :type="c.status === 'open' ? 'warning' : 'success'" :bordered="false">
              {{ c.status === 'open' ? '讨论中' : '已决策' }}
            </NTag>
          </div>
        </template>
        <p style="font-size:13px;color:var(--text-secondary);margin:0 0 6px;line-height:1.6">{{ c.patient_summary }}</p>
        <div style="display:flex;gap:12px;font-size:12px;color:var(--text-muted);flex-wrap:wrap">
          <span v-if="c.cancer_type">🔬 {{ c.cancer_type }}</span>
          <span>📄 {{ c.decisions?.length || 0 }} 条决策</span>
          <span>📎 {{ c.evidence_count }} 篇文献</span>
          <span>🕐 {{ toBeijingDate(c.created_at) }}</span>
        </div>
        <div v-if="c.status === 'open'" style="margin-top:8px">
          <NButton class="sky-btn" size="tiny" type="primary" ghost @click.stop="openDecide(c)">记录决策</NButton>
        </div>
      </NCard>
    </div>

    <!-- New case modal -->
    <NModal v-model:show="showNew" title="新建 MDT 病例" preset="card" style="width:520px">
      <NForm ref="formRef" :model="form" :rules="formRules" label-placement="top">
        <NFormItem path="title" label="病例标题">
          <NInput v-model:value="form.title" placeholder="右肺上叶占位 MDT 讨论" />
        </NFormItem>
        <NFormItem label="病例摘要（匿名化）">
          <NInput
            v-model:value="form.patient_summary"
            type="textarea" :rows="4"
            placeholder="患者性别/年龄/主诉/关键检查结果…"
          />
        </NFormItem>
        <NFormItem label="癌种">
          <NInput v-model:value="form.cancer_type" placeholder="肺癌 / 乳腺癌 / 结直肠癌…" />
        </NFormItem>
        <NButton class="sky-btn" type="primary" block :loading="saving" @click="createCase" style="margin-top:8px"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>创建病例</NButton>
      </NForm>
    </NModal>

    <!-- Decide modal -->
    <NModal v-model:show="showDecide" title="记录 MDT 决策" preset="card" style="width:540px">
      <NForm label-placement="top">
        <NFormItem label="MDT 结论">
          <NInput
            v-model:value="decisionForm.conclusion"
            type="textarea" :rows="3"
            placeholder="MDT 讨论结论……"
          />
        </NFormItem>
        <NFormItem label="参会人员（角色，如「张主任-外科」）">
          <NInput
            v-model:value="decisionForm.participants"
            placeholder="张主任-外科, 李医生-内科, 王教授-放疗"
          />
        </NFormItem>
        <NFormItem label="讨论日期">
          <NInput v-model:value="decisionForm.meeting_date" placeholder="2025-07-04" />
        </NFormItem>
        <NButton class="sky-btn" type="primary" block :loading="decideSaving" @click="submitDecision"><template #icon><NIcon size="14"><DocumentTextOutline /></NIcon></template>记录决策</NButton>
      </NForm>
    </NModal>

    <!-- Detail drawer -->
    <NDrawer v-model:show="showDetail" :width="560" placement="right">
      <NDrawerContent v-if="selectedCase" :title="selectedCase.title">
        <!-- Case info -->
        <NAlert type="info" style="margin-bottom:12px">
          <template #header>
            病例摘要
            <NTag size="tiny" :type="selectedCase.status === 'open' ? 'warning' : 'success'" style="margin-left:8px">
              {{ selectedCase.status === 'open' ? '讨论中' : '已决策' }}
            </NTag>
          </template>
          {{ selectedCase.patient_summary }}
        </NAlert>
        <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px">
          <span v-if="selectedCase.cancer_type">🔬 {{ selectedCase.cancer_type }} · </span>
          创建于 {{ toBeijingDate(selectedCase.created_at) }}
        </div>

        <!-- Decisions -->
        <div v-if="selectedCase.decisions?.length" style="margin-bottom:20px">
          <h4 style="margin:0 0 8px">📝 决策记录</h4>
          <NCard v-for="d in selectedCase.decisions" :key="d.id" size="small" style="margin-bottom:8px">
            <p style="font-size:13px;margin:0 0 6px;line-height:1.6">{{ d.conclusion }}</p>
            <div style="font-size:12px;color:var(--text-muted)">
              <div v-if="d.meeting_date">📅 {{ d.meeting_date?.slice(0, 10) }}</div>
              <div v-if="d.participants?.length" style="margin-top:4px">
                <span style="margin-right:4px">👥</span>
                <NTag
                  v-for="p in d.participants" :key="p"
                  size="tiny" :bordered="false"
                  :type="getRoleTagType(p.includes('-') ? p.split('-')[1] : '')"
                  style="margin-right:4px"
                >
                  {{ p }}
                </NTag>
              </div>
            </div>
          </NCard>
        </div>

        <NDivider />

        <!-- Evidence -->
        <div>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;flex-wrap:wrap;gap:6px">
            <h4 style="margin:0">📎 文献证据</h4>
            <div style="display:flex;gap:6px">
              <NButton class="sky-btn" size="tiny" @click="loadLiteraturePack">📦 文献包</NButton>
              <NButton class="sky-btn" size="tiny" @click="showAddEvidence = true">添加</NButton>
            </div>
          </div>
          <NSkeleton v-if="evidenceLoading" text :repeat="2" />
          <div v-else-if="!evidenceItems.length" style="font-size:13px;color:var(--text-muted);padding:16px 0;text-align:center">
            暂无文献证据
          </div>
          <NCard v-for="ev in evidenceItems" :key="ev.id" size="small" style="margin-bottom:8px">
            <div style="display:flex;justify-content:space-between;align-items:flex-start">
              <div style="flex:1">
                <a
                  :href="`/literature/${ev.pmid}`" target="_blank"
                  style="font-size:13px;font-weight:600;color:#1a5276;text-decoration:none"
                >
                  PMID: {{ ev.pmid }}
                </a>
                <div v-if="ev.citation" style="font-size:11px;color:var(--text-secondary);margin:4px 0;line-height:1.5">
                  {{ ev.citation.slice(0, 200) }}{{ ev.citation.length > 200 ? '…' : '' }}
                </div>
                <div v-if="ev.relevance_note" style="font-size:11px;color:var(--text-muted);margin-top:2px">
                  💬 {{ ev.relevance_note }}
                </div>
              </div>
              <NPopconfirm @positive="deleteEvidence(ev.id)">
                <template #trigger>
                  <NButton size="tiny" text style="color:var(--text-muted)">✕</NButton>
                </template>
                确认删除该证据？
              </NPopconfirm>
            </div>
          </NCard>
        </div>

        <!-- Add evidence -->
        <NDrawer v-model:show="showAddEvidence" :width="400" placement="right">
          <NDrawerContent title="添加文献证据">
            <NForm label-placement="top">
              <NFormItem label="PMID">
                <NInput v-model:value="addPmid" placeholder="39000101（支持多个，逗号分隔）" />
              </NFormItem>
              <NFormItem label="关联说明（可选）">
                <NInput
                  v-model:value="addNote" type="textarea" :rows="3"
                  placeholder="该文献与病例的关联……"
                />
              </NFormItem>
              <NButton class="sky-btn" type="primary" block :loading="evidenceLoading" @click="addEvidence"><template #icon><NIcon size="14"><CheckmarkCircleOutline /></NIcon></template>确认添加</NButton>
            </NForm>
          </NDrawerContent>
        </NDrawer>

        <!-- Literature pack drawer -->
        <NDrawer v-model:show="showLitPack" :width="500" placement="right">
          <NDrawerContent title="📦 文献包推荐">
            <div v-if="litPackLoading" style="text-align:center;padding:40px;color:var(--text-muted)">正在分析病例并检索相关文献...</div>
            <template v-else-if="!litPackItems.length">
              <div style="text-align:center;padding:40px;color:var(--text-muted)">
                <p>未找到相关文献推荐</p>
                <p style="font-size:12px;margin-top:8px">可手动添加 PMID 到文献证据</p>
              </div>
            </template>
            <template v-else>
              <div style="font-size:12px;color:var(--text-muted);margin-bottom:8px">
                基于搜索词 <NTag size="tiny" v-for="t in litPackTerms" :key="t" style="margin:0 2px">{{ t }}</NTag>
                推荐以下相关文献：
              </div>
              <div style="margin-bottom:10px;text-align:right">
                <NButton class="sky-btn" v-if="litPackItems.length" size="tiny" type="primary" :loading="addingPackPmids.size > 0" @click="addAllPack">一键添加全部</NButton>
              </div>
              <div style="display:flex;flex-direction:column;gap:8px">
                <NCard v-for="item in litPackItems" :key="item.pmid" size="small">
                  <div class="lit-row" style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px">
                    <div style="flex:1;min-width:0">
                      <div style="font-size:13px;font-weight:600;line-height:1.4;margin-bottom:4px">{{ item.title }}</div>
                      <div style="font-size:11px;color:var(--text-secondary);margin-bottom:4px">
                        <span>{{ item.first_author }} · </span>
                        <span>{{ item.journal }}</span>
                        <span v-if="item.pub_date"> · {{ (item.article_date || item.pub_date).slice(0,10) }}</span>
                      </div>
                      <div style="display:flex;gap:8px;font-size:11px;color:var(--text-muted);flex-wrap:wrap">
                        <span>📄 PMID: {{ item.pmid }}</span>
                        <span v-if="item.cited_by_count">📊 {{ item.cited_by_count }} 次引用</span>
                        <NTag size="tiny" :bordered="false" type="info">{{ item.reason }}</NTag>
                      </div>
                      <div v-if="item.tags?.length" style="margin-top:4px">
                        <NTag v-for="t in item.tags" :key="t" size="tiny" :bordered="false" style="margin-right:2px">{{ t }}</NTag>
                      </div>
                    </div>
                    <NButton class="sky-btn" size="tiny" type="primary" ghost
                      :loading="addingPackPmids.has(item.pmid)"
                      :disabled="addingPackPmids.has(item.pmid)"
                      @click="addPackLiterature(item.pmid)"
                      style="flex-shrink:0"
                    >
                      + 添加
                    </NButton>
                  </div>
                </NCard>
              </div>
            </template>
          </NDrawerContent>
        </NDrawer>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>

<style scoped>
.mdt-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

@media (max-width: 768px) {
  .mdt-container {
    padding: 12px;
  }

  .mdt-container h2 {
    font-size: 20px;
  }

  .lit-row {
    flex-wrap: wrap;
  }

  :deep(.n-modal) {
    width: 100% !important;
    max-width: calc(100vw - 24px) !important;
  }

  :deep(.n-drawer) {
    width: 100% !important;
    max-width: 100vw !important;
  }
}
</style>
