<script setup lang="ts">
import { ref, watch, computed, onMounted, onBeforeUnmount } from 'vue'
import { NDrawer, NDrawerContent, NTag, NButton, NSkeleton, NEmpty, NIcon } from 'naive-ui'
import { DocumentTextOutline } from '@vicons/ionicons5'
import { useToast } from '../../composables/useToast'
import { api } from '../../api/client'
import { computeStudyTypes } from '../../constants/studyTypes'
import { copyToClipboard } from '../../utils/clipboard'
import type { Author, LiteratureDetail } from '../../types'

const props = defineProps<{
  show: boolean
  pmid: number | null
}>()

const emit = defineEmits(['close', 'goDetail'])
const toast = useToast()

const windowWidth = ref(window.innerWidth)
const drawerWidth = computed(() => Math.min(560, windowWidth.value - 24))
function onResize() { windowWidth.value = window.innerWidth }
onMounted(() => window.addEventListener('resize', onResize))
onBeforeUnmount(() => window.removeEventListener('resize', onResize))

const lit = ref<LiteratureDetail | null>(null)
const loading = ref(false)

watch(() => props.show, async (v) => {
  if (v && props.pmid) {
    loading.value = true
    try {
      const { data } = await api.get('/public/literature/' + props.pmid)
      lit.value = data
    } catch (e) {
      toast.apiError(e, "加载文献详情失败")
      lit.value = null
    } finally {
      loading.value = false
    }
  } else if (!v) {
    lit.value = null
  }
})

async function copyPmid() {
  if (!lit.value?.pmid) return
  const ok = await copyToClipboard(String(lit.value.pmid))
  if (ok) toast.success('已复制 PMID')
  else toast.info(String(lit.value.pmid))
}

async function copyDoi() {
  if (!lit.value?.doi) return
  const ok = await copyToClipboard(lit.value.doi)
  if (ok) toast.success('已复制 DOI')
  else toast.info(lit.value.doi)
}

function formatAuthors(authors: Author[]): string {
  if (!authors?.length) return ''
  return authors.map(a => a.family || a.given || '').filter(Boolean).join(', ')
}

</script>

<template>
  <NDrawer :show="show" :width="drawerWidth" :placement="'right'" @update:show="v => !v && emit('close')">
    <NDrawerContent title="文献卡片详情" closable>
      <NSkeleton v-if="loading" text :repeat="12" />
      <NEmpty v-else-if="!lit" description="无法加载文献详情" />
      <template v-else>
        <!-- 标题 -->
        <h2 class="preview-title">{{ lit.title }}</h2>

        <!-- 研究类型徽章 -->
        <div v-if="lit.pub_types?.length" class="preview-type-row">
          <NTag v-for="st in computeStudyTypes(lit.pub_types)" :key="st.label" size="tiny" :type="st.type" :bordered="false">{{ st.label }}</NTag>
        </div>

        <!-- 元信息 -->
        <div class="preview-meta">
          <div v-if="lit.authors?.length" class="meta-row">
            <span class="meta-label">作者</span>
            <span>{{ formatAuthors(lit.authors) }}</span>
          </div>
          <div v-if="lit.affiliation" class="meta-row">
            <span class="meta-label">机构</span>
            <span class="meta-affil">🏛 {{ lit.affiliation }}</span>
          </div>
          <div v-if="lit.journal" class="meta-row">
            <span class="meta-label">期刊</span>
            <span><strong>{{ lit.journal }}</strong></span>
          </div>
          <div v-if="lit.pub_date" class="meta-row">
            <span class="meta-label">日期</span>
            <span>{{ (lit.article_date || lit.pub_date).slice(0, 10) }}</span>
          </div>
          <div v-if="lit.pmid" class="meta-row">
            <span class="meta-label">PMID</span>
            <span>{{ lit.pmid }} <span class="copy-btn" @click.stop="copyPmid" title="复制 PMID">📋</span></span>
          </div>
          <div v-if="lit.doi" class="meta-row">
            <span class="meta-label">DOI</span>
            <span>{{ lit.doi }} <span class="copy-btn" @click.stop="copyDoi" title="复制 DOI">📋</span></span>
          </div>
          <div v-if="lit.pmc_id" class="meta-row">
            <span class="meta-label">PMCID</span>
            <span>{{ lit.pmc_id }} <NTag v-if="lit.is_oa" type="success" size="tiny" :bordered="false">🔓 免费全文</NTag></span>
          </div>
          <div v-if="lit.cited_by_count" class="meta-row">
            <span class="meta-label">引用</span>
            <span>📊 被引 {{ lit.cited_by_count }} 次</span>
          </div>
        </div>

        <!-- 标签 -->
        <div v-if="lit.tags?.length" class="preview-tags">
          <NTag v-for="tag in lit.tags" :key="tag.id" size="small" :bordered="false">{{ tag.name_zh || tag.path }}</NTag>
        </div>

        <!-- 关键词 -->
        <div v-if="lit.keywords?.length" class="preview-section">
          <div class="preview-section-title">关键词</div>
          <div class="preview-keywords">
            <span v-for="kw in lit.keywords" :key="kw" class="kw-pill">{{ kw }}</span>
          </div>
        </div>

        <!-- GrantList -->
        <div v-if="lit.grants?.length" class="preview-section">
          <div class="preview-section-title">基金资助</div>
          <div v-for="(g, i) in lit.grants" :key="i" class="grant-row">
            <span v-if="g.agency">{{ g.agency }}</span>
            <span v-if="g.grant_id"> ({{ g.grant_id }})</span>
          </div>
        </div>

        <!-- 摘要 -->
        <div class="preview-section">
          <div class="preview-section-title">摘要</div>
          <p class="preview-abstract">{{ lit.abstract || '摘要不可用' }}</p>
        </div>

        <!-- AI 摘要 -->
        <div v-if="lit.ai_summary" class="preview-section">
          <div class="preview-section-title">AI 总结</div>
          <p class="preview-ai">{{ lit.ai_summary }}</p>
        </div>

        <!-- 操作 -->
        <div class="preview-actions">
          <NButton type="primary" @click="emit('goDetail', lit)" class="sky-btn"><template #icon><NIcon size="14"><DocumentTextOutline /></NIcon></template>阅读原文</NButton>
        </div>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.preview-title { font-size: 18px; font-weight: 700; line-height: 1.4; margin-bottom: 12px; }
.preview-type-row { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 12px; }
.preview-meta { margin-bottom: 16px; }
.meta-row { display: flex; gap: 8px; font-size: 13px; margin-bottom: 5px; }
.meta-label { color: var(--text-muted); flex-shrink: 0; min-width: 44px; }
.meta-affil { color: var(--kw-pill-color); }
html.dark .meta-affil { color: #6ab0e0; }
.copy-btn { cursor: pointer; font-size: 12px; }
.preview-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 16px; }
.preview-section { margin-bottom: 18px; }
.preview-section-title { font-size: 13px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
.preview-abstract { font-size: 13px; color: var(--text-primary); line-height: 1.7; white-space: pre-wrap; }
.preview-ai { font-size: 13px; background: var(--preview-ai-bg); padding: 10px; border-radius: 6px; }
.preview-keywords { display: flex; flex-wrap: wrap; gap: 4px; }
.kw-pill { font-size: 12px; background: var(--kw-pill-bg); color: var(--kw-pill-color); padding: 2px 8px; border-radius: 10px; }
.grant-row { font-size: 12px; color: var(--text-primary); margin-bottom: 2px; }
.preview-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
</style>
