<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import * as statsApi from '@/api/stats'
import { Cpu, HardDrive, MemoryStick, Clock, TrendingUp, Tag } from 'lucide-vue-next'

const reloadPage = () => globalThis.location.reload()
import SectionHeader from '@/components/stats/SectionHeader.vue'
import MetricCard from '@/components/stats/MetricCard.vue'
import MiniLineChart from '@/components/stats/MiniLineChart.vue'
import MiniBarChart from '@/components/stats/MiniBarChart.vue'

type DailyPoint = { date: string; count: number }
type HourlyPoint = { hour: number; count: number }

const isLoading = ref(true)
const hasError = ref(false)

// 数据状态
const systemHealth = ref<any>(null)
const conversationStats = ref<any>(null)
const knowledgeStats = ref<any>(null)
const kanbanStats = ref<any>(null)
const communityStats = ref<any>(null)
const personalInsights = ref<any>(null)

function formatUptime(seconds: number) {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const mins = Math.floor((seconds % 3600) / 60)
  if (days > 0) return `${days}d ${hours}h`
  if (hours > 0) return `${hours}h ${mins}m`
  return `${mins}m`
}

function formatNumber(num: number): string {
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
  return num.toString()
}

onMounted(async () => {
  try {
    // 系统健康不需要认证
    const sys = await statsApi.getSystemHealth().catch(() => null)
    systemHealth.value = sys?.data || null

    // 用户相关数据需要认证
    const [conv, know, kanban, community, insights] = await Promise.all([
      statsApi.getConversationStats().catch(() => null),
      statsApi.getKnowledgeStats().catch(() => null),
      statsApi.getKanbanStats().catch(() => null),
      statsApi.getCommunityStats().catch(() => null),
      statsApi.getPersonalInsights().catch(() => null),
    ])
    conversationStats.value = conv?.data || null
    knowledgeStats.value = know?.data || null
    kanbanStats.value = kanban?.data || null
    communityStats.value = community?.data || null
    personalInsights.value = insights?.data || null
  } catch (e) {
    hasError.value = true
    console.error('Failed to load stats:', e)
  } finally {
    isLoading.value = false
  }
})

// 图表数据转换
const convChartData = computed(() =>
  conversationStats.value?.daily_conversations?.map((d: DailyPoint) => ({ date: d.date, value: d.count })) || []
)

const knowChartData = computed(() =>
  knowledgeStats.value?.daily_new_tags?.map((d: DailyPoint) => ({ date: d.date, value: d.count })) || []
)

const kanbanNewData = computed(() =>
  kanbanStats.value?.daily_new_tasks?.map((d: DailyPoint) => d.count) || []
)
const kanbanDoneData = computed(() =>
  kanbanStats.value?.daily_completed_tasks?.map((d: DailyPoint) => d.count) || []
)

const communityChartData = computed(() =>
  communityStats.value?.daily_posts?.map((d: DailyPoint) => ({ date: d.date, value: d.count })) || []
)

const hourlyActivityData = computed(() =>
  personalInsights.value?.hourly_activity?.map((h: HourlyPoint) => h.count) || []
)

const convBarValues = computed(() => convChartData.value.map((d: { date: string; value: number }) => d.value))
const knowBarValues = computed(() => knowChartData.value.map((d: { date: string; value: number }) => d.value))
const communityBarValues = computed(() => communityChartData.value.map((d: { date: string; value: number }) => d.value))
</script>

<template>
  <div class="stats-view">
    <div class="stats-header">
      <h1>// 运行状态</h1>
    </div>

    <div v-if="isLoading" class="loading-state">
      <div class="loading-spinner"></div>
      <span>Loading metrics...</span>
    </div>

    <div v-else-if="hasError" class="error-state">
      <span>Failed to load stats</span>
      <button @click="reloadPage">Refresh</button>
    </div>

    <div v-else class="stats-content">
      <!-- SYSTEM HEALTH -->
      <section class="stats-section">
        <SectionHeader title="SYSTEM HEALTH" tag="cyan" />
        <div class="metrics-grid">
          <MetricCard
            :icon="Cpu"
            label="CPU Usage"
            :value="systemHealth ? systemHealth.cpu_percent + '%' : '--'"
            accentColor="var(--accent-cyan)"
          />
          <MetricCard
            :icon="MemoryStick"
            label="Memory"
            :value="systemHealth ? systemHealth.memory_percent + '%' : '--'"
            accentColor="var(--accent-purple)"
          />
          <MetricCard
            :icon="HardDrive"
            label="Disk"
            :value="systemHealth ? systemHealth.disk_percent + '%' : '--'"
            accentColor="var(--accent-amber)"
          />
          <MetricCard
            :icon="Clock"
            label="Uptime"
            :value="systemHealth ? formatUptime(systemHealth.uptime_seconds) : '--'"
            accentColor="var(--accent-green)"
          />
        </div>
      </section>

      <!-- CONVERSATIONS -->
      <section class="stats-section">
        <SectionHeader title="沟通系统" tag="cyan" />
        <div class="stats-metrics-grid-4">
          <div class="stat-bar-item">
            <div class="stat-bar-label">对话数</div>
            <div class="stat-bar-value">{{ formatNumber(conversationStats?.totals?.conversations || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="convChartData.length > 0" :data="convBarValues" color="var(--accent-cyan)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">消息数</div>
            <div class="stat-bar-value">{{ formatNumber(conversationStats?.totals?.messages || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="convChartData.length > 0" :data="convBarValues" color="var(--accent-purple)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">输入Token</div>
            <div class="stat-bar-value">{{ formatNumber(conversationStats?.totals?.input_tokens || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniLineChart v-if="convChartData.length > 0" :data="convChartData" color="var(--accent-amber)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">输出Token</div>
            <div class="stat-bar-value">{{ formatNumber(conversationStats?.totals?.output_tokens || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniLineChart v-if="convChartData.length > 0" :data="convChartData" color="var(--accent-green)" :height="30" />
            </div>
          </div>
        </div>
      </section>

      <!-- KNOWLEDGE -->
      <section class="stats-section">
        <SectionHeader title="知识库" tag="purple" />
        <div class="stats-metrics-row">
          <div class="stat-bar-item">
            <div class="stat-bar-label">新标签</div>
            <div class="stat-bar-value">{{ formatNumber(knowledgeStats?.totals?.new_tags || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="knowChartData.length > 0" :data="knowBarValues" color="var(--accent-purple)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">文档数</div>
            <div class="stat-bar-value">{{ formatNumber(knowledgeStats?.totals?.documents || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="knowChartData.length > 0" :data="knowBarValues" color="var(--accent-cyan)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">标签关联</div>
            <div class="stat-bar-value">{{ formatNumber(knowledgeStats?.totals?.tag_relations || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniLineChart v-if="knowChartData.length > 0" :data="knowChartData" color="var(--accent-amber)" :height="30" />
            </div>
          </div>
        </div>
      </section>

      <!-- KANBAN -->
      <section class="stats-section">
        <SectionHeader title="任务矩阵" tag="cyan" />
        <div class="stats-metrics-row">
          <div class="stat-bar-item">
            <div class="stat-bar-label">待处理</div>
            <div class="stat-bar-value">{{ kanbanStats?.current_pending_tasks || 0 }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart :data="kanbanNewData" color="var(--accent-amber)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">新建(30天)</div>
            <div class="stat-bar-value">{{ formatNumber(kanbanStats?.totals?.new_tasks || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart :data="kanbanNewData" color="var(--accent-cyan)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">完成(30天)</div>
            <div class="stat-bar-value">{{ formatNumber(kanbanStats?.totals?.completed_tasks || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart :data="kanbanDoneData" color="var(--accent-green)" :height="30" />
            </div>
          </div>
        </div>
      </section>

      <!-- COMMUNITY -->
      <section class="stats-section">
        <SectionHeader title="信息交易所" tag="amber" />
        <div class="stats-metrics-row">
          <div class="stat-bar-item">
            <div class="stat-bar-label">帖子数</div>
            <div class="stat-bar-value">{{ formatNumber(communityStats?.totals?.posts || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="communityChartData.length > 0" :data="communityBarValues" color="var(--accent-amber)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">回复数</div>
            <div class="stat-bar-value">{{ formatNumber(communityStats?.totals?.replies || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniBarChart v-if="communityChartData.length > 0" :data="communityBarValues" color="var(--accent-purple)" :height="30" />
            </div>
          </div>
          <div class="stat-bar-item">
            <div class="stat-bar-label">AI执行</div>
            <div class="stat-bar-value">{{ formatNumber(communityStats?.totals?.ai_executions || 0) }}</div>
            <div class="stat-bar-chart">
              <MiniLineChart v-if="communityChartData.length > 0" :data="communityChartData" color="var(--accent-cyan)" :height="30" />
            </div>
          </div>
        </div>
      </section>

      <!-- INSIGHTS -->
      <section class="stats-section">
        <SectionHeader title="个人洞察" tag="cyan" />
        <div class="insights-grid" v-if="personalInsights">
          <div class="insight-card">
            <h4>Hourly Activity</h4>
            <MiniBarChart
              v-if="hourlyActivityData.length > 0"
              :data="hourlyActivityData"
              color="var(--accent-cyan)"
              :height="80"
              :maxBars="24"
            />
            <div v-else class="empty-state small">No activity data</div>
          </div>
          <div class="insight-card">
            <h4>Top Tags</h4>
            <ul class="tag-list" v-if="personalInsights.top_tags?.length">
              <li v-for="tag in personalInsights.top_tags" :key="tag.tag_path">
                <Tag :size="12" />
                <span class="tag-name">{{ tag.tag_path }}</span>
                <span class="tag-count">{{ tag.usage_count }}</span>
              </li>
            </ul>
            <div v-else class="empty-state small">No tags yet</div>
          </div>
          <div class="insight-card">
            <h4>Token Trend</h4>
            <div class="token-trend">
              <span class="trend-value" :class="personalInsights.token_trend_percent > 0 ? 'up' : 'down'">
                <TrendingUp :size="16" />
                {{ personalInsights.token_trend_percent }}%
              </span>
              <span class="trend-label">vs last month</span>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <span>Login to see personal insights</span>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.stats-view {
  height: 100%;
  overflow-y: auto;
  padding: 24px;
  background: var(--bg-void);
}

.stats-header {
  margin-bottom: 24px;
}

.stats-header h1 {
  font-family: var(--font-mono);
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 0.15em;
  color: var(--accent-cyan);
}

.stats-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stats-metrics-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stats-metrics-grid-4 {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-bar-item {
  background: var(--bg-card);
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-md);
  padding: 16px;
}

.stat-bar-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.1em;
  color: var(--text-dim);
  text-transform: uppercase;
  margin-bottom: 4px;
}

.stat-bar-value {
  font-family: var(--font-mono);
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.stat-bar-chart {
  margin-top: 8px;
  min-height: 30px;
}

.stats-section {
  background: rgba(10, 15, 26, 0.6);
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-lg);
  padding: 20px;
  margin-bottom: 16px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

@media (max-width: 1199px) {
  .metrics-grid { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 767px) {
  .metrics-grid { grid-template-columns: 1fr; }
}

.chart-box {
  background: var(--bg-card);
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-md);
  padding: 16px;
}

.chart-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.1em;
  color: var(--text-dim);
  text-transform: uppercase;
  margin-bottom: 12px;
}

.bar-chart-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.insights-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

@media (max-width: 1199px) {
  .insights-grid { grid-template-columns: 1fr 1fr; }
}

@media (max-width: 767px) {
  .insights-grid { grid-template-columns: 1fr; }
}

.insight-card {
  background: var(--bg-card);
  border: 1px solid var(--border-dim);
  border-radius: var(--radius-md);
  padding: 16px;
}

.insight-card h4 {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.1em;
  color: var(--text-dim);
  text-transform: uppercase;
  margin-bottom: 12px;
}

.tag-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tag-list li {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  border-bottom: 1px solid var(--border-dim);
  font-size: 12px;
}

.tag-list li:last-child {
  border-bottom: none;
}

.tag-name {
  flex: 1;
  color: var(--text-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag-count {
  font-family: var(--font-mono);
  color: var(--accent-cyan);
  font-size: 11px;
}

.token-trend {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 0;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: var(--font-mono);
  font-size: 24px;
  font-weight: 600;
}

.trend-value.up {
  color: var(--accent-red);
}

.trend-value.down {
  color: var(--accent-green);
}

.trend-label {
  font-family: var(--font-mono);
  font-size: 9px;
  color: var(--text-dim);
  letter-spacing: 0.08em;
  text-transform: uppercase;
}

.loading-state,
.error-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: var(--text-dim);
  font-family: var(--font-mono);
  font-size: 12px;
  gap: 12px;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid var(--border-dim);
  border-top-color: var(--accent-cyan);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state.small {
  padding: 20px;
}

button {
  padding: 8px 16px;
  background: var(--accent-cyan-dim);
  border: 1px solid var(--border-mid);
  border-radius: var(--radius-md);
  color: var(--accent-cyan);
  font-family: var(--font-mono);
  font-size: 11px;
  cursor: pointer;
  transition: all var(--transition-fast);
}

button:hover {
  background: rgba(0, 245, 212, 0.2);
  box-shadow: var(--glow-cyan);
}
</style>
