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

const message = useMessage()

function fmtPipelineTime(ts: string | null | undefined): string {
  if (!ts) return '—'
  return new Date(ts + 'Z').toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false,
  }).replace(/\//g, '-')
}

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

interface DashboardStats {
  tenants?: number
  users?: number
  literature?: number
  wau_7d?: number
  [key: string]: unknown
}
interface DataQuality {
  total: number
  with_abstract: number
  with_fulltext: number
  tagged: number
  with_pico: number
  with_study_design: number
  with_cited_by: number
  with_doi: number
}
interface Pipeline {
  type?: string
  status?: string
  new?: number
  feeds?: number
  completed?: string
  [key: string]: unknown
}

const stats = ref<DashboardStats>({})
const quality = ref<DataQuality>({ total: 0, with_abstract: 0, with_fulltext: 0, tagged: 0, with_pico: 0, with_study_design: 0, with_cited_by: 0, with_doi: 0 })
const pipelines = ref<Pipeline[]>([])
const dailyStats = ref<any[]>([])
const loading = ref(true)
const tagDistribution = ref<Record<string, number>>({})

const qualityItems = computed(() => [
  { label: '有摘要', value: quality.value.with_abstract, total: quality.value.total, color: '#2080f0' },
  { label: '已打标', value: quality.value.tagged, total: quality.value.total, color: '#18a058' },
  { label: '有引用次数', value: quality.value.with_cited_by, total: quality.value.total, color: '#f0a020' },
  { label: '有研究设计', value: quality.value.with_study_design, total: quality.value.total, color: '#7c4dff' },
  { label: '有DOI', value: quality.value.with_doi, total: quality.value.total, color: '#008080' },
  { label: '有OA全文', value: quality.value.with_fulltext, total: quality.value.total, color: '#d03050' },
  { label: '有PICO', value: quality.value.with_pico, total: quality.value.total, color: '#808080' },
])

onMounted(async () => {
  try {
    const [dashR, tagsR] = await Promise.all([api.get('/admin/dashboard'), api.get('/admin/tags')])
    stats.value = (dashR.data?.stats || {}) as DashboardStats
    quality.value = (dashR.data?.data_quality || { total:0, with_abstract:0, with_fulltext:0, tagged:0, with_pico:0, with_study_design:0, with_cited_by:0, with_doi:0 }) as DataQuality
    pipelines.value = (dashR.data?.recent_pipelines || []) as Pipeline[]
    dailyStats.value = (dashR.data?.daily_pipeline_stats || []) as any[]
    const tc: Record<string, number> = {}
    for (const [cat, tags] of Object.entries(tagsR.data?.tags || {})) tc[cat] = (tags as unknown[]).length
    tagDistribution.value = tc
  } catch (e: any) {
    message.error(e?.response?.data?.detail || '加载仪表盘失败')
  } finally { loading.value = false }
})

const barData = computed(() => ({
  labels: ['租户', '用户', '文献(K)', '7日活跃'],
  datasets: [{ label:'数量', data:[stats.value.tenants||0, stats.value.users||0, Math.round((stats.value.literature||0)/1000), stats.value.wau_7d||0], backgroundColor: ['#2080f0','#18a058','#f0a020','#7c4dff'] }]
}))

const doughnutData = computed(() => ({
  labels: Object.keys(tagDistribution.value),
  datasets: [{ data: Object.values(tagDistribution.value), backgroundColor: ['#2080f0','#18a058','#f0a020','#d03050','#7c4dff','#008080'] }]
}))

const pipeCols = [
  { title: '类型', key: 'type', width: 80 },
  { title: '状态', key: 'status', width: 60, render: (r: Pipeline) => h(NTag, { type: r.status === 'success' ? 'success' : 'error', size: 'tiny' as const }, () => r.status) },
  { title: '新增', key: 'new', width: 50 },
  { title: 'Feed', key: 'feeds', width: 50 },
  { title: '完成', key: 'completed', width: 140, render: (r: Pipeline) => fmtPipelineTime(r.completed) },
]

const dailyCols = [
  { title: '类型', key: 'type', width: 80 },
  { title: '执行次数', key: 'count', width: 70 },
  { title: '新增文献', key: 'new_articles', width: 80 },
  { title: 'Feed推送', key: 'feeds', width: 80 },
]

const catLabels: Record<string,string> = { cancer:'癌种', gene:'靶点', treatment:'治疗', study_type:'研究类型', endpoint:'终点', scenario:'场景' }
</script>

<template>
  <div>
    <NSkeleton v-if="loading" text :repeat="8" />
    <template v-else>
      <!-- Top stats cards -->
      <n-grid :cols="4" :x-gap="12" responsive="screen" class="stat-grid" style="margin-bottom:20px">
        <n-grid-item><n-card size="small"><n-statistic label="租户" :value="stats.tenants||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="用户" :value="stats.users||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="文献" :value="stats.literature||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="7日活跃" :value="stats.wau_7d||0"/></n-card></n-grid-item>
      </n-grid>

      <!-- Charts row -->
      <n-grid :cols="2" :x-gap="16" responsive="screen" class="chart-grid" style="margin-bottom:20px">
        <n-grid-item>
          <n-card title="📊 系统概览" size="small">
            <Bar :data="barData" :options="{responsive:true,plugins:{legend:{display:false}}}" style="max-height:220px" />
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="🏷️ 标签分布" size="small">
            <Doughnut :data="doughnutData" :options="{responsive:true,plugins:{legend:{position:'bottom',labels:{font:{size:10},generateLabels:(chart:any)=>chart.data.labels.map((l:string,i:number)=>({text:catLabels[l]||l,fillStyle:chart.data.datasets[0].backgroundColor[i],hidden:false,index:i}))}}}}" style="max-height:220px" />
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- Data quality section -->
      <n-card title="📋 数据质量" size="small" style="margin-bottom:20px">
        <n-grid :cols="qualityItems.length > 5 ? 4 : qualityItems.length" :x-gap="16" :y-gap="16" responsive="screen">
          <n-grid-item v-for="item in qualityItems" :key="item.label">
            <div style="font-size:12px;color:var(--text-secondary);margin-bottom:4px">{{ item.label }}</div>
            <NProgress
              type="line"
              :percentage="item.total > 0 ? Math.round(item.value / item.total * 100) : 0"
              :color="item.color"
              :height="12"
              :border-radius="6"
              :fill-border-radius="6"
            />
            <div style="font-size:11px;color:var(--text-tertiary);margin-top:2px;text-align:right">
              {{ item.value }} / {{ item.total }}
            </div>
          </n-grid-item>
        </n-grid>
      </n-card>

      <!-- Daily pipeline stats -->
      <n-grid :cols="2" :x-gap="16" responsive="screen" style="margin-bottom:20px">
        <n-grid-item>
          <n-card title="📡 最近管道运行" size="small">
            <n-data-table :columns="pipeCols" :data="pipelines" size="small" :bordered="false" :paginate="pipelines.length > 10 ? {pageSize:10} : false" />
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="📈 近7天管道统计" size="small">
            <n-data-table v-if="dailyStats.length" :columns="dailyCols" :data="dailyStats" size="small" :bordered="false" />
            <div v-else style="font-size:13px;color:var(--text-tertiary);padding:12px">近7天暂无管道运行</div>
          </n-card>
        </n-grid-item>
      </n-grid>
    </template>
  </div>
</template>

<style scoped>
@media (max-width: 768px) {
  .stat-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
  .chart-grid {
    grid-template-columns: 1fr !important;
  }
}
</style>
