<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { NCard, NSelect, NSkeleton, NAlert, NButton, NTag, NIcon } from 'naive-ui'
import { CheckmarkCircleOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'

interface GuidelineItem {
  id: string
  source: string
  version: string
  publish_date: string
  change_summary_zh: string | null
  pdf_url: string | null
  source_url: string | null
}

const guidelines = ref<GuidelineItem[]>([])
const loading = ref(true)
const source = ref('NCCN')
const fromVer = ref('')
const toVer = ref('')
const comparison = ref<any>(null)
const compareLoading = ref(false)

onMounted(async () => {
  try {
    const { data } = await api.get('/approvals/guidelines')
    guidelines.value = data.items || []
    // 自动选择最新两个版本
    autoSelectVersions()
  } finally { loading.value = false }
})

// 按 source 过滤
const filtered = computed(() => guidelines.value.filter((g: any) => g.source === source.value))

// 按 version 排序（降序）
const sortedFiltered = computed(() => {
  return [...filtered.value].sort((a, b) => b.version.localeCompare(a.version, undefined, { numeric: true }))
})

const versions = computed(() => sortedFiltered.value.map(g => g.version))

// 获取指定版本的 pdf_url
const fromPdfUrl = computed(() => sortedFiltered.value.find(g => g.version === fromVer.value)?.pdf_url || null)
const toPdfUrl = computed(() => sortedFiltered.value.find(g => g.version === toVer.value)?.pdf_url || null)

function autoSelectVersions() {
  const v = sortedFiltered.value
  if (v.length >= 2) {
    const last = v[v.length - 2]
    const first = v[0]
    if (last) fromVer.value = last.version
    if (first) toVer.value = first.version
    if (last && first) doCompare()
  } else if (v.length === 1) {
    const first = v[0]
    if (first) toVer.value = first.version
  }
}

watch(source, () => {
  fromVer.value = ''
  toVer.value = ''
  comparison.value = null
  autoSelectVersions()
})

async function doCompare() {
  if (!fromVer.value || !toVer.value) return
  compareLoading.value = true
  try {
    const { data } = await api.get(`/approvals/guidelines/changes/${source.value}/${fromVer.value}/${toVer.value}`)
    comparison.value = data
  } finally { compareLoading.value = false }
}

// LCS-based word-level diff
function wordDiff(oldText: string | null, newText: string | null): Array<{ type: 'equal' | 'insert' | 'delete', value: string }> {
  const a = oldText || '', b = newText || ''
  const tokenize = (s: string) => s.match(/[一-鿿\w]+|[^一-鿿\w]/g) || []
  const oldTokens = tokenize(a), newTokens = tokenize(b)
  const m = oldTokens.length, n = newTokens.length
  // LCS table
  const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0))
  for (let i = 1; i <= m; i++)
    for (let j = 1; j <= n; j++)
      dp[i]![j] = oldTokens[i - 1]! === newTokens[j - 1]!
        ? dp[i - 1]![j - 1]! + 1
        : Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!)
  // Backtrack
  const result: Array<{ type: 'equal' | 'insert' | 'delete', value: string }> = []
  let i = m, j = n
  while (i > 0 || j > 0) {
    if (i > 0 && j > 0 && oldTokens[i - 1] === newTokens[j - 1]) {
      result.unshift({ type: 'equal', value: oldTokens[i - 1]! })
      i--; j--
    } else if (j > 0 && (i === 0 || dp[i]![j - 1]! >= dp[i - 1]![j]!)) {
      result.unshift({ type: 'insert', value: newTokens[j - 1]! })
      j--
    } else {
      result.unshift({ type: 'delete', value: oldTokens[i - 1]! })
      i--
    }
  }
  return result
}

const diffSpans = computed(() => {
  const fromSummary = comparison.value?.from?.summary
  const toSummary = comparison.value?.to?.summary
  if (!fromSummary && !toSummary) return []
  return wordDiff(fromSummary ?? '', toSummary ?? '')
})

const evidenceDiff = computed(() => comparison.value?.evidence_diff || null)

const sourceOptions = [
  { label: 'NCCN', value: 'NCCN' },
  { label: 'CSCO', value: 'CSCO' },
  { label: 'ESMO', value: 'ESMO' },
  { label: 'NHC', value: 'NHC' },
]
</script>

<template>
  <div style="max-width:900px;margin:0 auto;padding:32px 24px">
    <h1 style="margin-bottom:8px">📋 指南变更对比</h1>
    <p style="color:var(--text-secondary);margin-bottom:24px">对比新旧版本指南的差异，高亮临床实践变化</p>

    <NSkeleton v-if="loading" text :repeat="4" />

    <NCard v-else size="small" style="margin-bottom:24px">
      <div style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
        <div>
          <span style="font-size:12px;color:var(--text-muted)">机构</span>
          <NSelect v-model:value="source" :options="sourceOptions" size="small" style="width:120px" />
        </div>
        <div>
          <span style="font-size:12px;color:var(--text-muted)">旧版</span>
          <NSelect v-model:value="fromVer" :options="versions.map(v => ({ value: v, label: v }))" size="small" style="width:140px" />
        </div>
        <div>
          <span style="font-size:12px;color:var(--text-muted)">新版</span>
          <NSelect v-model:value="toVer" :options="versions.map(v => ({ value: v, label: v }))" size="small" style="width:140px" />
        </div>
        <NButton type="primary" size="small" :loading="compareLoading" :disabled="!fromVer || !toVer" @click="doCompare" class="sky-btn"><template #icon><NIcon size="14"><CheckmarkCircleOutline /></NIcon></template>对比</NButton>
      </div>
    </NCard>

    <NSkeleton v-if="compareLoading" text :repeat="3" />

    <template v-else-if="comparison">
      <div v-if="comparison.from && comparison.to">
        <!-- Side-by-side comparison -->
        <div style="display:flex;gap:16px;margin-bottom:20px;flex-wrap:wrap">
          <NCard :title="`旧版 ${comparison.from.version}`" size="small" style="flex:1;min-width:300px">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
              <NTag size="tiny" :bordered="false">{{ comparison.from.date }}</NTag>
              <NButton v-if="fromPdfUrl" size="tiny" text tag="a" :href="fromPdfUrl" target="_blank">📄 PDF</NButton>
            </div>
            <div style="font-size:13px;line-height:1.8;white-space:pre-wrap">
              <span v-for="(part, idx) in diffSpans" :key="idx"
                    :style="part.type === 'delete' ? 'background:var(--diff-delete-bg);color:var(--diff-delete-text);text-decoration:line-through' : ''">{{ part.value }}</span>
            </div>
          </NCard>

          <NCard :title="`新版 ${comparison.to.version}`" size="small" style="flex:1;min-width:300px">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
              <NTag size="tiny" type="success" :bordered="false">{{ comparison.to.date }}</NTag>
              <NButton v-if="toPdfUrl" size="tiny" text tag="a" :href="toPdfUrl" target="_blank">📄 PDF</NButton>
            </div>
            <div style="font-size:13px;line-height:1.8;white-space:pre-wrap">
              <span v-for="(part, idx) in diffSpans" :key="idx"
                    :style="part.type === 'insert' ? 'background:var(--diff-insert-bg);color:var(--diff-insert-text)' : ''">{{ part.value }}</span>
            </div>
          </NCard>
        </div>

        <!-- Diff highlights -->
        <NCard v-if="diffSpans.length" title="🔍 变更要点" size="small">
          <div style="font-size:13px;line-height:1.8">
            <span v-for="(part, idx) in diffSpans" :key="idx"
                  :style="part.type === 'insert' ? 'background:var(--diff-insert-bg);color:var(--diff-insert-text)' :
                          part.type === 'delete' ? 'background:var(--diff-delete-bg);color:var(--diff-delete-text);text-decoration:line-through' : ''">{{ part.value }}</span>
          </div>
        </NCard>

        <!-- 证据变更 -->
        <NCard v-if="evidenceDiff && (evidenceDiff.added.length || evidenceDiff.removed.length || evidenceDiff.changed.length)" title="🔬 方案变更" size="small" style="margin-top:16px">
          <div v-if="evidenceDiff.removed.length" style="margin-bottom:12px">
            <h4 style="margin:0 0 6px 0;font-size:13px">❌ 移除的方案</h4>
            <div v-for="ev in evidenceDiff.removed" :key="ev.pmid" style="padding:6px 8px;background:var(--diff-delete-bg);border-radius:4px;margin-bottom:4px;font-size:13px">
              <div style="display:flex;gap:4px;margin-bottom:2px">
                <NTag size="tiny" type="error">{{ ev.level||'—' }}</NTag>
                <NTag v-if="ev.treatment_line" size="tiny">{{ ev.treatment_line }}</NTag>
              </div>
              <div style="text-decoration:line-through;color:var(--diff-delete-text)">{{ ev.recommendation }}</div>
              <div v-if="ev.pmid" style="font-size:11px;color:var(--text-muted);margin-top:2px">PMID {{ ev.pmid }}</div>
            </div>
          </div>

          <div v-if="evidenceDiff.added.length" style="margin-bottom:12px">
            <h4 style="margin:0 0 6px 0;font-size:13px">🆕 新增的方案</h4>
            <div v-for="ev in evidenceDiff.added" :key="ev.pmid" style="padding:6px 8px;background:var(--diff-insert-bg);border-radius:4px;margin-bottom:4px;font-size:13px">
              <div style="display:flex;gap:4px;margin-bottom:2px">
                <NTag size="tiny" type="success">{{ ev.level||'—' }}</NTag>
                <NTag v-if="ev.treatment_line" size="tiny">{{ ev.treatment_line }}</NTag>
              </div>
              <div>{{ ev.recommendation }}</div>
              <div v-if="ev.pmid" style="font-size:11px;color:var(--text-muted);margin-top:2px">PMID {{ ev.pmid }}</div>
            </div>
          </div>

          <div v-if="evidenceDiff.changed.length">
            <h4 style="margin:0 0 6px 0;font-size:13px">🔄 推荐的变更</h4>
            <div v-for="ev in evidenceDiff.changed" :key="ev.pmid" style="padding:6px 8px;background:var(--diff-insert-bg);border-left:3px solid #f0a020;border-radius:4px;margin-bottom:4px;font-size:13px">
              <div style="display:flex;gap:4px;margin-bottom:2px">
                <NTag size="tiny" :type="ev.changes?.level ? 'warning' : 'success'">{{ ev.level||'—' }}</NTag>
                <NTag v-if="ev.treatment_line" size="tiny">{{ ev.treatment_line }}</NTag>
              </div>
              <div>{{ ev.recommendation }}</div>
              <div v-if="ev.changes" style="margin-top:4px;font-size:12px">
                <div v-if="ev.changes.recommendation" style="color:#999">
                  推荐变更：<span style="text-decoration:line-through;color:var(--diff-delete-text)">{{ ev.changes.recommendation[0] }}</span>
                  → <span style="color:var(--diff-insert-text)">{{ ev.changes.recommendation[1] }}</span>
                </div>
                <div v-if="ev.changes.treatment_line" style="color:#999">
                  线数变更：{{ ev.changes.treatment_line[0] }} → {{ ev.changes.treatment_line[1] }}
                </div>
                <div v-if="ev.changes.level" style="color:#999">
                  级别变更：{{ ev.changes.level[0] }} → {{ ev.changes.level[1] }}
                </div>
              </div>
              <div v-if="ev.pmid" style="font-size:11px;color:var(--text-muted);margin-top:2px">PMID {{ ev.pmid }}</div>
            </div>
          </div>
        </NCard>

        <!-- Version history -->
        <NCard title="📊 版本历史" size="small" style="margin-top:16px">
          <div style="display:flex;flex-wrap:wrap;gap:8px">
            <NTag v-for="g in sortedFiltered" :key="g.version"
              :type="g.version === toVer ? 'success' : g.version === fromVer ? 'warning' : 'default'"
              size="small" :bordered="false"
              style="cursor:pointer"
              @click="g.version !== toVer ? (fromVer = g.version !== fromVer ? fromVer : toVer, toVer = g.version, doCompare()) : null"
            >
              {{ g.version }}
              <template #avatar>
                <span v-if="g.pdf_url" @click.stop>📄</span>
              </template>
            </NTag>
          </div>
        </NCard>
      </div>

      <NAlert v-else type="warning" style="margin-top:16px" title="无法获取版本信息。请确认选择了正确的版本。" />
    </template>

    <div v-else style="text-align:center;padding:40px;color:var(--text-muted)">
      选择版本后点击"对比"
    </div>
  </div>
</template>
