<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NCard, NGrid, NGridItem, NButton, NSkeleton, NEmpty, NProgress, NModal, NIcon } from 'naive-ui'
import { SettingsOutline } from '@vicons/ionicons5'
import { Line } from 'vue-chartjs'
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend, Filler } from 'chart.js'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const toast = useToast()

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend, Filler)

interface DomainItem {
  tag_id: string
  name: string
  match_mode: string
  recent_count: number
  total_count: number
  category: string
  [key: string]: unknown
}

interface TrendPoint {
  week_start: string
  count: number
  [key: string]: unknown
}

interface TrendResponse {
  total: number
  trends: TrendPoint[]
  [key: string]: unknown
}

const router = useRouter()
const domains = ref<DomainItem[]>([])
const byCategory = ref<Record<string, DomainItem[]>>({})
const loading = ref(true)
const showTrendModal = ref(false)
const showTrend = ref<DomainItem | null>(null)
const trendData = ref<TrendResponse | null>(null)
const trendLoading = ref(false)

const catLabels: Record<string,string> = { cancer:'癌种部位', gene:'驱动基因/靶点', treatment:'治疗方式', study_type:'研究类型', endpoint:'临床终点', scenario:'临床场景' }
const catIcons: Record<string,string> = { cancer:'🎗️', gene:'🧬', treatment:'💊', study_type:'📊', endpoint:'📈', scenario:'🏥' }
const catColors: Record<string,string> = { cancer:'#2080f0', gene:'#18a058', treatment:'#f0a020', study_type:'#d03050', endpoint:'#7c4dff', scenario:'#008080' }

onMounted(loadData)
async function loadData() {
  try {
    const { data } = await api.get('/domains/center')
    domains.value = data.domains || []
    byCategory.value = data.by_category || {}
  } catch (e) { toast.apiError(e, '加载领域中心失败') }
  finally { loading.value = false }
}
async function viewTrend(domain: DomainItem) {
  showTrend.value = domain; showTrendModal.value = true; trendLoading.value = true
  try {
    const { data } = await api.get(`/domains/trends/${domain.tag_id}?weeks=12`)
    trendData.value = data
  } catch (e) { toast.apiError(e, '加载趋势数据失败') }
  finally { trendLoading.value = false }
}
function goSearch(domain: DomainItem) {
  showTrendModal.value = false; router.push(`/app/search?tag=${domain.tag_id}`)
}

const lineData = computed(() => {
  if (!trendData.value) return { labels:[], datasets:[] }
  return {
    labels: trendData.value.trends.map((t: TrendPoint) => t.week_start.slice(5)),
    datasets: [{
      label: '文献数', data: trendData.value.trends.map((t: TrendPoint) => t.count),
      borderColor: catColors[showTrend.value?.category || ''] || '#1a5276',
      backgroundColor: (catColors[showTrend.value?.category || ''] || '#1a5276') + '20',
      fill: true, tension: 0.3, pointRadius: 3,
    }]
  }
})
</script>

<template>
  <div style="max-width:1400px;margin:0 auto;padding:24px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
      <div>
        <h2 style="margin:0">🎯 领域中心</h2>
        <p style="color:var(--text-secondary);font-size:13px;margin:4px 0 0">已关注 {{ domains.length }} 个研究领域</p>
      </div>
      <NButton @click="router.push('/app/settings/interests')" class="sky-btn"><template #icon><NIcon size="14"><SettingsOutline /></NIcon></template>管理关注领域</NButton>
    </div>

    <NSkeleton v-if="loading" text :repeat="6" />
    <NEmpty v-else-if="!domains.length" description="还没有关注任何领域">
      <template #extra>
        <NButton type="primary" @click="router.push('/app/settings/interests')" class="sky-btn"><template #icon><NIcon size="14"><SettingsOutline /></NIcon></template>去设置关注领域</NButton>
      </template>
    </NEmpty>

    <div v-else v-for="(domains, cat) in byCategory" :key="cat" style="margin-bottom:24px" :class="cat === 'cancer' ? 'cancer-section' : ''">
      <NCard :title="`${catIcons[cat]||'📌'} ${catLabels[cat]||cat}`" size="small">
        <NGrid :cols="cat === 'cancer' ? 3 : 3" :x-gap="8" :y-gap="8" responsive="screen">
          <NGridItem v-for="d in domains" :key="d.tag_id">
            <NCard size="small" hoverable style="cursor:pointer;text-align:center" @click="viewTrend(d)">
              <div style="font-weight:600;margin-bottom:4px">{{ d.name }}</div>
              <div style="font-size:11px;color:var(--text-muted);margin-bottom:8px">{{ d.match_mode==='standard'?'标准':'宽松' }}匹配</div>
              <NGrid :cols="2" :x-gap="4">
                <NGridItem><div style="font-size:10px;color:var(--text-muted)">本周</div><div style="font-size:18px;font-weight:700;color:#1a5276">{{ d.recent_count }}</div></NGridItem>
                <NGridItem><div style="font-size:10px;color:var(--text-muted)">总计</div><div style="font-size:18px;font-weight:700">{{ d.total_count }}</div></NGridItem>
              </NGrid>
              <NProgress type="line" :percentage="Math.min(100, Math.round(d.recent_count/Math.max(1,d.total_count)*100))" :height="4" style="margin-top:6px" />
            </NCard>
          </NGridItem>
        </NGrid>
      </NCard>
    </div>

    <!-- 领域趋势弹窗 -->
    <NModal v-model:show="showTrendModal" title="领域追踪" preset="card" style="width:650px" v-if="showTrend">
      <template #header><span style="font-weight:600">{{ showTrend.name }}</span></template>
      <NSkeleton v-if="trendLoading" height="300" />
      <div v-else>
        <Line :data="lineData" :options="{ responsive:true, interaction:{intersect:false}, scales:{y:{beginAtZero:true,title:{display:true,text:'文献数/周'}}} }" style="max-height:280px" />
        <div v-if="trendData?.trends" style="margin-top:12px;display:flex;justify-content:space-between;font-size:11px;color:var(--text-muted)">
          <span v-for="t in trendData.trends.slice(-6)" :key="t.week_start">
            {{ t.week_start.slice(5) }}: <strong>{{ t.count }}</strong>
          </span>
        </div>
      </div>
      <NButton class="sky-btn" size="small" style="margin-top:8px" @click="goSearch(showTrend)">🔍 搜索该领域文献</NButton>
    </NModal>
  </div>
</template>

<style scoped>
.cancer-section :deep(.n-card .n-card__content) > div:first-child {
  font-size: 15px;
}
</style>
