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

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

const toast = useToast()

interface Stats {
  saved?: number
  notes?: number
  subscriptions?: number
  read_rate?: number
  total_feed?: number
  read?: number
  active_days_7d?: number
  rated?: number
  [key: string]: unknown
}
interface JournalItem {
  journal: string
  count: number
  [key: string]: unknown
}
interface TagItem {
  name: string
  count: number
  [key: string]: unknown
}

const router = useRouter()
const loading = ref(true)
const stats = ref<Stats>({})
const topJournals = ref<JournalItem[]>([])
const topTags = ref<TagItem[]>([])
const weeklyLoading = ref(false)

onMounted(async () => {
  try {
    const { data } = await api.get('/settings/profile')
    stats.value = data.stats || {}
    topJournals.value = data.top_journals || []
    topTags.value = data.top_tags || []
  } catch (e) { toast.apiError(e, '加载学术画像失败') }
  finally { loading.value = false }
})

const maxTagCount = computed(() => Math.max(1, ...topTags.value.map((t: TagItem) => t.count), 1))

const journalChart = computed(() => ({
  labels: topJournals.value.map((j: JournalItem) => j.journal.slice(0, 25)),
  datasets: [{
    label: '收藏篇数',
    data: topJournals.value.map((j: JournalItem) => j.count),
    backgroundColor: ['#2080f0', '#18a058', '#d03050', '#f0a020', '#7c4dff'],
    borderRadius: 3,
  }],
}))

async function downloadWeeklyReport() {
  weeklyLoading.value = true
  try {
    const { data } = await api.get('/settings/profile/weekly-report', { responseType: 'blob' })
    const blob = new Blob([data], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url; a.download = `阅读周报_${new Date().toISOString().slice(0, 10)}.md`
    a.click(); URL.revokeObjectURL(url)
    toast.success('周报已下载')
  } catch (e) { toast.apiError(e, '生成周报失败') }
  finally { weeklyLoading.value = false }
}
</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">
      <h2 style="margin:0">📊 我的学术画像</h2>
      <NButton type="primary" ghost size="small" :loading="weeklyLoading" @click="downloadWeeklyReport" class="sky-btn">
        📥 下载阅读周报
      </NButton>
    </div>
    <NSkeleton v-if="loading" text :repeat="6" />
    <template v-else>
      <!-- 核心指标 -->
      <n-grid :cols="4" :x-gap="12" responsive="screen" style="margin-bottom:24px">
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="收藏文献" :value="stats.saved||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="阅读笔记" :value="stats.notes||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="关注标签" :value="stats.subscriptions||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="阅读率" :value="`${stats.read_rate||0}%`"/></n-card></n-grid-item>
      </n-grid>

      <n-grid :cols="4" :x-gap="12" responsive="screen" style="margin-bottom:24px">
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="待阅读" :value="stats.total_feed||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="已阅读" :value="stats.read||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="已评分" :value="stats.rated||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small" style="text-align:center"><n-statistic label="7日活跃天" :value="stats.active_days_7d||0"/></n-card></n-grid-item>
      </n-grid>

      <!-- 阅读进度 -->
      <n-card title="📈 阅读进度" size="small" style="margin-bottom:16px">
        <div style="display:flex;align-items:center;gap:12px">
          <n-progress type="circle" :percentage="stats.read_rate||0" :height="80" :stroke-width="8" color="#1a5276" />
          <div style="font-size:13px;color:var(--text-secondary);line-height:1.6">
            <div>本周活跃天数：<strong>{{ stats.active_days_7d||0 }} / 7 天</strong></div>
            <div style="margin-top:4px">共推送 <strong>{{ stats.total_feed||0 }}</strong> 篇，已读 <strong>{{ stats.read||0 }}</strong> 篇</div>
          </div>
        </div>
      </n-card>

      <!-- 标签分布 -->
      <n-card title="🏷️ 关注领域分布" size="small" style="margin-bottom:16px">
        <div v-if="topTags.length">
          <div v-for="t in topTags.slice(0,12)" :key="t.name" style="margin-bottom:8px;display:flex;align-items:center;gap:8px">
            <span style="width:70px;font-size:11px;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{{ t.name }}</span>
            <n-progress type="line" :percentage="Math.round(t.count/maxTagCount*100)" :height="14" :border-radius="3" :color="'#1a5276'" style="flex:1" />
            <span style="width:24px;font-size:11px;color:var(--text-muted);text-align:right">{{ t.count }}</span>
          </div>
        </div>
        <div v-else style="color:var(--text-muted);font-size:13px;text-align:center;padding:16px">
          暂无数据。去<a href="/app/settings/interests" style="color:#1a5276">设置关注领域</a>开始使用。
        </div>
      </n-card>

      <!-- Top 期刊图表 -->
      <n-grid :cols="2" :x-gap="16" responsive="screen" style="margin-bottom:16px">
        <n-grid-item>
          <n-card title="📰 最常收藏期刊" size="small">
            <div v-if="topJournals.length">
              <Bar v-if="topJournals.length" :data="journalChart" :options="{ responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } } }" style="max-height:200px" />
            </div>
            <div v-else style="color:var(--text-muted);text-align:center;padding:16px;font-size:13px">还没有收藏文献。</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="🎯 快速入口" size="small">
            <div style="display:flex;flex-direction:column;gap:8px;padding:8px 0">
              <NButton type="primary" ghost @click="router.push('/app/settings/interests')" class="sky-btn">🎯 设置关注领域</NButton>
              <NButton ghost @click="router.push('/app/feed')" class="sky-btn">📰 文献速览</NButton>
              <NButton ghost @click="router.push('/app/library')" class="sky-btn">📚 查看收藏</NButton>
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>
    </template>
  </div>
</template>
