<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { NCard, NGrid, NGridItem, NStatistic, NSkeleton, NTag, useMessage } from 'naive-ui'
import { Bar, Pie, Line } 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 { toBeijingDateTime } from '../../utils/date'

const message = useMessage()

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

interface TenantInfo { plan_type: string; [key: string]: unknown }
interface DashboardStats { tenants: number; users: number; literature: number; wau_7d: number; saved: number; notes: number; [key: string]: unknown }
interface PipelineRun { type: string; status: string; new: number; feeds: number; completed: string | null }

const loading = ref(true)
const stats = ref<DashboardStats>({} as DashboardStats)
const tenantList = ref<TenantInfo[]>([])
const feedbackCount = ref(0)
const userGrowth = ref<{year: number; month: number; count: number}[]>([])
const pipelines = ref<PipelineRun[]>([])
const tagCategories = ref<{category: string; count: number; articles: number}[]>([])
const dauData = ref<{date: string; count: number}[]>([])
const pipelineTrend = ref<PipelineRun[]>([])
const pageViews = ref<{date: string; pv: number; uv: number}[]>([])
const anonPageViews = ref<{date: string; pv: number; uv: number}[]>([])
const behaviors = ref<{type: string; count: number}[]>([])
const popularPages = ref<{type: string; id: string; count: number}[]>([])

// ── Phase 3 新增 ──
const sessionTrend = ref<{date: string; sessions: number; unique_users: number; avg_duration_seconds: number}[]>([])
const funnel = ref<{step: string; label: string; users: number; conversion_rate: number}[]>([])
const retention = ref<{cohort: string; total: number; weeks: {week: number; active_users: number; retention_rate: number}[]}[]>([])

onMounted(async () => {
  try {
    const [dashR, tenantsR, feedbackR, growthR, tagsR, dauR, pipelineR, pvR, anonPvR, behR, popR, sessR, funR, retR] = await Promise.all([
      api.get('/admin/dashboard'),
      api.get('/admin/tenants', { params: { page_size: 100 } }),
      api.get('/settings/feedback'),
      api.get('/admin/users/growth'),
      api.get('/admin/tags/distribution'),
      api.get('/admin/stats/dau', { params: { days: 30 } }),
      api.get('/admin/pipeline/runs', { params: { page_size: 30 } }),
      api.get('/admin/stats/page-views', { params: { days: 30 } }),
      api.get('/admin/stats/anonymous-page-views', { params: { days: 30 } }),
      api.get('/admin/stats/anonymous-page-views', { params: { days: 30 } }),
      api.get('/admin/stats/behavior', { params: { days: 7 } }),
      api.get('/admin/stats/popular-pages', { params: { days: 7, limit: 20 } }),
      api.get('/analytics/sessions/trend', { params: { days: 30 } }).catch(() => ({ data: { items: [] } })),
      api.get('/analytics/funnel', { params: { days: 30 } }).catch(() => ({ data: { funnel: [] } })),
      api.get('/analytics/retention', { params: { weeks: 12 } }).catch(() => ({ data: { cohorts: [] } })),
    ])
    stats.value = dashR.data.stats || {}
    pipelines.value = dashR.data.recent_pipelines || []
    tenantList.value = tenantsR.data.items || []
    feedbackCount.value = (feedbackR.data.items || []).length
    userGrowth.value = growthR.data.growth || []
    tagCategories.value = tagsR.data.categories || []
    dauData.value = dauR.data.dau || []
    pipelineTrend.value = (pipelineR.data.items || []).reverse()
    pageViews.value = pvR.data.page_views || []
    anonPageViews.value = anonPvR.data.page_views || []
    behaviors.value = behR.data.behaviors || []
    popularPages.value = popR.data.pages || []
    sessionTrend.value = (sessR as any)?.data?.items || []
    funnel.value = (funR as any)?.data?.funnel || []
    retention.value = (retR as any)?.data?.cohorts || []
  } catch (e: any) {
    message.error(e?.response?.data?.detail || '加载分析数据失败')
  } finally { loading.value = false }
})

const revenueData = computed(() => ({
  labels: ['Free', 'Pro', 'Team', 'Enterprise'],
  datasets: [{
    label: '租户数',
    data: [
      tenantList.value.filter((t: TenantInfo) => t.plan_type === 'free').length,
      tenantList.value.filter((t: TenantInfo) => t.plan_type === 'pro').length,
      tenantList.value.filter((t: TenantInfo) => t.plan_type === 'team').length,
    ],
    backgroundColor: ['#999', '#2080f0', '#18a058'],
  }],
}))

const growthData = computed(() => ({
  labels: userGrowth.value.map((g: {year: number; month: number}) => `${g.year}-${String(g.month).padStart(2, '0')}`),
  datasets: [{
    label: '新增用户',
    data: userGrowth.value.map((g: {count: number}) => g.count),
    borderColor: '#2080f0',
    backgroundColor: 'rgba(32,128,240,0.1)',
    fill: true,
    tension: 0.3,
  }],
}))

const tagPieData = computed(() => ({
  labels: tagCategories.value.map((c: {category: string}) => c.category),
  datasets: [{
    data: tagCategories.value.map((c: {count: number}) => c.count),
    backgroundColor: ['#2080f0', '#18a058', '#d03050', '#f0a020', '#7c4dff', '#eb2f96', '#13c2c2', '#fa8c16'],
  }],
}))

const estimatedMRR = computed(() => {
  return tenantList.value.filter((t: TenantInfo) => t.plan_type === 'pro').length * 35 +
    tenantList.value.filter((t: TenantInfo) => t.plan_type === 'team').length * 70 * 5
})

const dauChartData = computed(() => ({
  labels: dauData.value.map((d: {date: string}) => {
    const parts = d.date.split('-')
    return `${parts[1]}/${parts[2]}`
  }),
  datasets: [{
    label: '日活跃用户',
    data: dauData.value.map((d: {count: number}) => d.count),
    borderColor: '#18a058',
    backgroundColor: 'rgba(24,160,88,0.1)',
    fill: true,
    tension: 0.3,
  }],
}))

const pageViewChartData = computed(() => ({
  labels: pageViews.value.map((d) => {
    const parts = d.date.split('-')
    return `${parts[1]}/${parts[2]}`
  }),
  datasets: [
    {
      label: 'PV',
      data: pageViews.value.map((d) => d.pv),
      borderColor: '#2080f0',
      backgroundColor: 'rgba(32,128,240,0.1)',
      fill: true,
      tension: 0.3,
      yAxisID: 'y',
    },
    {
      label: 'UV',
      data: pageViews.value.map((d) => d.uv),
      borderColor: '#18a058',
      backgroundColor: 'rgba(24,160,88,0.1)',
      fill: true,
      tension: 0.3,
      yAxisID: 'y1',
    },
  ],
}))

const anonPageViewChartData = computed(() => ({
  labels: anonPageViews.value.map((d) => {
    const parts = d.date.split('-')
    return `${parts[1]}/${parts[2]}`
  }),
  datasets: [
    {
      label: '匿名PV',
      data: anonPageViews.value.map((d) => d.pv),
      borderColor: '#f0a020',
      backgroundColor: 'rgba(240,160,32,0.1)',
      fill: true,
      tension: 0.3,
      yAxisID: 'y',
    },
    {
      label: '匿名UV',
      data: anonPageViews.value.map((d) => d.uv),
      borderColor: '#d03050',
      backgroundColor: 'rgba(208,48,80,0.1)',
      fill: true,
      tension: 0.3,
      yAxisID: 'y1',
    },
  ],
}))

const behaviorPieData = computed(() => ({
  labels: behaviors.value.map((b) => b.type),
  datasets: [{
    data: behaviors.value.map((b) => b.count),
    backgroundColor: ['#2080f0', '#18a058', '#d03050', '#f0a020', '#7c4dff', '#eb2f96', '#13c2c2', '#fa8c16'],
  }],
}))

const pipelineVolumeData = computed(() => ({
  labels: pipelineTrend.value.map((p: PipelineRun) =>
    p.completed ? p.completed.slice(5, 10) : '--'
  ),
  datasets: [
    {
      label: '新增文献',
      data: pipelineTrend.value.map((p: PipelineRun) => p.new || 0),
      backgroundColor: '#2080f0',
      borderRadius: 3,
    },
    {
      label: '生成推送',
      data: pipelineTrend.value.map((p: PipelineRun) => p.feeds || 0),
      backgroundColor: '#18a058',
      borderRadius: 3,
    },
  ],
}))

const sessionChartData = computed(() => ({
  labels: sessionTrend.value.map((d: any) => {
    const parts = d.date.split('-')
    return `${parts[1]}/${parts[2]}`
  }),
  datasets: [{
    label: '会话数',
    data: sessionTrend.value.map((d: any) => d.sessions),
    borderColor: '#7c4dff',
    backgroundColor: 'rgba(124,77,255,0.1)',
    fill: true,
    tension: 0.3,
  }],
}))

const funnelChartData = computed(() => ({
  labels: funnel.value.map((f: any) => f.label),
  datasets: [{
    label: '用户数',
    data: funnel.value.map((f: any) => f.users),
    backgroundColor: ['#2080f0', '#18a058', '#f0a020', '#d03050', '#7c4dff'],
    borderRadius: 3,
  }],
}))

const todaySessionStats = computed(() => {
  const today = sessionTrend.value[sessionTrend.value.length - 1]
  if (!today) return { sessions: 0, avgDuration: 0, uniqueUsers: 0 }
  return {
    sessions: today.sessions || 0,
    avgDuration: today.avg_duration_seconds || 0,
    uniqueUsers: today.unique_users || 0,
  }
})
</script>

<template>
  <div>
    <h2 style="margin-bottom:16px">运营分析</h2>
    <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"><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>

      <n-grid :cols="4" :x-gap="12" responsive="screen" style="margin-bottom:24px">
        <n-grid-item><n-card size="small"><n-statistic label="用户反馈" :value="feedbackCount||0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="估算MRR" :value="`¥${estimatedMRR||0}`"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="人均收藏" :value="stats.users ? Math.round((stats.saved||0)/(stats.users||1)) : 0"/></n-card></n-grid-item>
        <n-grid-item><n-card size="small"><n-statistic label="文献/人" :value="stats.users ? Math.round((stats.literature||0)/(stats.users||1)) : 0"/></n-card></n-grid-item>
      </n-grid>

      <!-- 图表行（2×2） -->
      <n-grid :cols="2" :x-gap="16" :y-gap="16" responsive="screen" style="margin-bottom:24px">
        <n-grid-item>
          <n-card title="方案分布" size="small">
            <Bar :data="revenueData" :options="{ responsive: true, plugins: { legend: { display: false } } }" style="max-height:200px" />
            <div style="text-align:center;margin-top:8px;font-size:12px;color:var(--text-secondary)">MRR：¥{{ estimatedMRR }}/月</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="用户增长趋势" size="small">
            <Line v-if="userGrowth.length" :data="growthData" :options="{ responsive: true, plugins: { legend: { display: false } } }" style="max-height:200px" />
            <div v-else style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无增长数据</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="标签分类分布" size="small">
            <Pie v-if="tagCategories.length" :data="tagPieData" :options="{ responsive: true, plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 10 } } } } }" style="max-height:200px" />
            <div v-else style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无标签数据</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="日活跃用户 (近30天)" size="small">
            <Line v-if="dauData.length" :data="dauChartData" :options="{ responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } } }" style="max-height:200px" />
            <div v-else style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无登录数据</div>
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- 管道运行趋势 -->
      <n-card title="管道运行量趋势" size="small" style="margin-bottom:24px">
        <Bar v-if="pipelineTrend.length" :data="pipelineVolumeData" :options="{ responsive: true, plugins: { legend: { position: 'top', labels: { boxWidth: 10, font: { size: 11 } } } }, scales: { x: { ticks: { maxRotation: 45, font: { size: 10 } } }, y: { beginAtZero: true } } }" style="max-height:250px" />
        <div v-else style="height:100px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无运行记录</div>
      </n-card>

      <!-- 流水线 + 指标 -->
      <n-grid :cols="2" :x-gap="16" responsive="screen">
        <n-grid-item>
          <n-card title="最近管道运行" size="small">
            <div v-if="pipelines.length">
              <div v-for="(p,i) in pipelines" :key="i" style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
                <div>
                  <NTag size="tiny" :type="p.status==='completed'?'success':'warning'" :bordered="false">{{ p.status }}</NTag>
                  <span style="margin-left:6px">{{ p.type }}</span>
                </div>
                <div style="color:var(--text-muted)">
                  <span v-if="p.new>0">+{{ p.new }}篇 </span>
                  <span v-if="p.completed">{{ toBeijingDateTime(p.completed) || '—' }}</span>
                </div>
              </div>
            </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="padding:8px">
              <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
                <span>平均每租户用户</span><strong>{{ stats.tenants ? (stats.users/stats.tenants).toFixed(1) : 0 }}</strong>
              </div>
              <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
                <span>笔记总量</span><strong>{{ stats.notes||0 }}</strong>
              </div>
              <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
                <span>收藏总量</span><strong>{{ stats.saved||0 }}</strong>
              </div>
              <div style="display:flex;justify-content:space-between;padding:8px 0;font-size:13px">
                <span>付费转化率</span>
                <strong>{{ stats.tenants ? Math.round(tenantList.filter((t: TenantInfo)=>t.plan_type!=='free').length/stats.tenants*100) : 0 }}%</strong>
              </div>
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- 页面访问趋势 -->
      <n-card title="页面访问趋势 (近30天)" size="small" style="margin-bottom:24px">
        <div style="font-size:13px;color:var(--text-muted);margin-bottom:8px">注册用户</div>
        <Line v-if="pageViews.length" :data="pageViewChartData" :options="{ responsive: true, plugins: { legend: { position: 'top', labels: { boxWidth: 10, font: { size: 11 } } } }, scales: { y: { beginAtZero: true, type: 'linear', position: 'left' }, y1: { beginAtZero: true, type: 'linear', position: 'right', grid: { display: false } } } }" style="max-height:220px" />
        <div v-else style="height:80px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无注册用户访问数据</div>

        <div style="border-top:1px solid var(--border-color);margin:16px 0" />

        <div style="font-size:13px;color:var(--text-muted);margin-bottom:8px">匿名用户</div>
        <Line v-if="anonPageViews.length" :data="anonPageViewChartData" :options="{ responsive: true, plugins: { legend: { position: 'top', labels: { boxWidth: 10, font: { size: 11 } } } }, scales: { y: { beginAtZero: true, type: 'linear', position: 'left' }, y1: { beginAtZero: true, type: 'linear', position: 'right', grid: { display: false } } } }" style="max-height:220px" />
        <div v-else style="height:80px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无匿名用户访问数据</div>
      </n-card>

      <!-- 用户行为 + 热门页面 -->
      <n-grid :cols="2" :x-gap="16" responsive="screen" style="margin-bottom:24px">
        <n-grid-item>
          <n-card title="用户行为分布 (近7天)" size="small">
            <Pie v-if="behaviors.length" :data="behaviorPieData" :options="{ responsive: true, plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 10 } } } } }" style="max-height:200px" />
            <div v-else style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无行为数据</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="热门页面 (近7天)" size="small">
            <div v-if="popularPages.length">
              <div v-for="(p,i) in popularPages.slice(0,10)" :key="i" style="display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid var(--border-color);font-size:13px">
                <div>
                  <span style="color:var(--text-muted);margin-right:6px">{{ i + 1 }}.</span>
                  <span>{{ p.id || p.type }}</span>
                </div>
                <NTag size="tiny" :bordered="false">{{ p.count }}次</NTag>
              </div>
            </div>
            <div v-else style="height:100px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无热门页面数据</div>
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- ── Phase 3: 会话分析 + 漏斗 + 留存 ── -->
      <n-grid :cols="2" :x-gap="16" :y-gap="16" responsive="screen" style="margin-bottom:24px">
        <n-grid-item>
          <n-card title="会话分析" size="small">
            <n-grid :cols="3" :x-gap="8" style="margin-bottom:12px">
              <n-grid-item><n-statistic label="今日会话" :value="todaySessionStats.sessions" /></n-grid-item>
              <n-grid-item><n-statistic label="平均时长" :value="`${Math.round(todaySessionStats.avgDuration)}s`" /></n-grid-item>
              <n-grid-item><n-statistic label="独立用户" :value="todaySessionStats.uniqueUsers" /></n-grid-item>
            </n-grid>
            <Line v-if="sessionTrend.length" :data="sessionChartData" :options="{ responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } }" style="max-height:200px" />
            <div v-else style="height:100px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无会话数据</div>
          </n-card>
        </n-grid-item>
        <n-grid-item>
          <n-card title="行为漏斗" size="small">
            <Bar v-if="funnel.length" :data="funnelChartData" :options="{ responsive: true, indexAxis: 'y', plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true } } }" style="max-height:200px" />
            <div v-else style="height:100px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无漏斗数据</div>
            <div v-if="funnel.length" style="margin-top:8px">
              <div v-for="f in funnel" :key="f.step" style="display:flex;justify-content:space-between;padding:3px 0;font-size:12px">
                <span>{{ f.label }}</span>
                <span><strong>{{ f.users }}</strong> 人 · {{ f.conversion_rate }}%</span>
              </div>
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>

      <!-- 留存分析 -->
      <n-card title="留存分析 (周级 Cohort)" size="small" style="margin-bottom:24px">
        <div v-if="retention.length" style="overflow-x:auto">
          <table style="border-collapse:collapse;font-size:12px;width:100%">
            <thead>
              <tr>
                <th style="padding:6px 8px;text-align:left;border:1px solid var(--border-color);background:var(--bg-hover)">Cohort</th>
                <th style="padding:6px 8px;text-align:right;border:1px solid var(--border-color);background:var(--bg-hover)">用户数</th>
                <th v-for="i in 8" :key="i" style="padding:6px 4px;text-align:center;border:1px solid var(--border-color);background:var(--bg-hover)">W{{ i-1 }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="c in retention.slice(0,10)" :key="c.cohort">
                <td style="padding:4px 8px;border:1px solid var(--border-color);white-space:nowrap">{{ c.cohort.slice(5) }}</td>
                <td style="padding:4px 8px;border:1px solid var(--border-color);text-align:right">{{ c.total }}</td>
                <td v-for="w in c.weeks.slice(0,8)" :key="w.week"
                  style="padding:4px;border:1px solid var(--border-color);text-align:center"
                  :style="{ background: `rgba(32,128,240,${Math.max(0.05, w.retention_rate / 100)})` }">
                  {{ w.retention_rate > 0 ? w.retention_rate + '%' : '-' }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-else style="height:60px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);font-size:13px">暂无留存数据（需要更多用户活动积累）</div>
      </n-card>
    </template>
  </div>
</template>