<template>
  <div class="dashboard-overview">
    <div class="overview-cards">
      <a-card hoverable class="overview-card" @click="openDrawer('tasks')">
        <a-statistic
          title="总任务数"
          :value="metrics?.total_tasks ?? 0"
          :value-style="{ color: '#7c3aed' }"
        >
          <template #prefix><CheckCircleOutlined /></template>
        </a-statistic>
      </a-card>
      <a-card hoverable class="overview-card" @click="openDrawer('agents')">
        <a-statistic
          title="Agent 活跃数"
          :value="activeAgentCount"
          :value-style="{ color: '#7c3aed' }"
        >
          <template #prefix><TeamOutlined /></template>
        </a-statistic>
      </a-card>
      <a-card hoverable class="overview-card" @click="openDrawer('usage')">
        <a-statistic
          title="LLM 用量"
          :value="usageSummary.total_tokens"
          :value-style="{ color: '#3b82f6' }"
        >
          <template #prefix><CloudServerOutlined /></template>
        </a-statistic>
        <div class="overview-card__footer">{{ usageSummary.total_requests }} 次请求</div>
      </a-card>
      <a-card hoverable class="overview-card" @click="openDrawer('metrics')">
        <a-statistic
          title="质量通过率"
          :value="metrics ? (metrics.success_rate * 100).toFixed(1) : '0.0'"
          suffix="%"
          :value-style="{ color: '#10b981' }"
        >
          <template #prefix><SafetyCertificateOutlined /></template>
        </a-statistic>
      </a-card>
    </div>

    <div class="overview-sections">
      <div class="overview-section">
        <div class="overview-section__header">
          <h3>最近经验</h3>
          <a-button type="link" size="small" @click="openDrawer('experiences')">查看全部</a-button>
        </div>
        <div v-if="recentExperiences.length === 0" class="overview-section__empty">
          <a-empty description="暂无经验记录" :image-style="{ height: '40px' }" />
        </div>
        <div v-else class="overview-section__list">
          <div
            v-for="exp in recentExperiences"
            :key="exp.id"
            class="experience-item"
            @click="openDrawer('experience-detail', exp)"
          >
            <div class="experience-item__dot" :class="`experience-item__dot--${exp.outcome}`" />
            <div class="experience-item__info">
              <span class="experience-item__goal">{{ exp.goal || exp.task_type }}</span>
              <span class="experience-item__meta">{{ exp.task_type }} · {{ formatTime(exp.created_at) }}</span>
            </div>
            <a-tag :color="exp.outcome === 'success' ? 'success' : 'error'" size="small">
              {{ exp.outcome === 'success' ? '成功' : '失败' }}
            </a-tag>
          </div>
        </div>
      </div>

      <div class="overview-section">
        <div class="overview-section__header">
          <h3>避坑预警</h3>
          <a-button type="link" size="small" @click="openDrawer('pitfalls')">查看全部</a-button>
        </div>
        <div v-if="store.pitfalls.length === 0" class="overview-section__empty">
          <a-empty description="暂无预警信息" :image-style="{ height: '40px' }" />
        </div>
        <div v-else class="overview-section__list">
          <div
            v-for="(warning, index) in store.pitfalls.slice(0, 5)"
            :key="index"
            class="pitfall-item"
            @click="openDrawer('pitfall-detail', warning)"
          >
            <a-tag :color="riskColor(warning.risk_level)" size="small">
              {{ riskLabel(warning.risk_level) }}
            </a-tag>
            <span class="pitfall-item__step">{{ warning.step }}</span>
            <span class="pitfall-item__rate">{{ (warning.historical_failure_rate * 100).toFixed(0) }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Detail Drawer -->
    <a-drawer
      v-model:open="drawerVisible"
      :title="drawerTitle"
      placement="right"
      :width="520"
      :destroy-on-close="true"
    >
      <div class="drawer-content">
        <!-- Task list -->
        <template v-if="drawerType === 'tasks'">
          <div v-if="store.experiences.length === 0" class="drawer-empty">
            <a-empty description="暂无任务记录" />
          </div>
          <div v-for="exp in store.experiences" :key="exp.id" class="drawer-task-item">
            <div class="drawer-task-item__header">
              <span class="drawer-task-item__goal">{{ exp.goal || exp.task_type }}</span>
              <a-tag :color="exp.outcome === 'success' ? 'success' : 'error'" size="small">
                {{ exp.outcome === 'success' ? '完成' : '失败' }}
              </a-tag>
            </div>
            <div class="drawer-task-item__meta">
              <span>{{ exp.task_type }}</span>
              <span>{{ formatDuration(exp.duration) }}</span>
              <span>{{ formatTime(exp.created_at) }}</span>
            </div>
          </div>
        </template>

        <!-- Experience list -->
        <template v-if="drawerType === 'experiences'">
          <div v-if="store.experiences.length === 0" class="drawer-empty">
            <a-empty description="暂无经验记录" />
          </div>
          <div v-for="exp in store.experiences" :key="exp.id" class="drawer-exp-item" @click="openDrawer('experience-detail', exp)">
            <div class="drawer-exp-item__dot" :class="`drawer-exp-item__dot--${exp.outcome}`" />
            <div class="drawer-exp-item__body">
              <div class="drawer-exp-item__header">
                <span class="drawer-exp-item__goal">{{ exp.goal || exp.task_type }}</span>
                <a-tag :color="exp.outcome === 'success' ? 'success' : 'error'" size="small">
                  {{ exp.outcome === 'success' ? '成功' : '失败' }}
                </a-tag>
              </div>
              <div class="drawer-exp-item__meta">{{ exp.task_type }} · {{ formatDuration(exp.duration) }} · {{ formatTime(exp.created_at) }}</div>
            </div>
          </div>
        </template>

        <!-- Experience detail -->
        <template v-if="drawerType === 'experience-detail' && experienceData">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="目标">{{ experienceData.goal || experienceData.task_type }}</a-descriptions-item>
            <a-descriptions-item label="类型">{{ experienceData.task_type }}</a-descriptions-item>
            <a-descriptions-item label="结果">
              <a-tag :color="experienceData.outcome === 'success' ? 'success' : 'error'">
                {{ experienceData.outcome === 'success' ? '成功' : '失败' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="耗时">{{ formatDuration(experienceData.duration) }}</a-descriptions-item>
            <a-descriptions-item label="时间">{{ formatTime(experienceData.created_at) }}</a-descriptions-item>
          </a-descriptions>
          <div v-if="experienceData.steps_summary" class="detail-block">
            <div class="detail-block__title">步骤摘要</div>
            <div class="detail-block__text">{{ experienceData.steps_summary }}</div>
          </div>
          <div v-if="experienceData.failure_reasons?.length" class="detail-block">
            <div class="detail-block__title">失败原因</div>
            <ul class="detail-block__list">
              <li v-for="(reason, i) in experienceData.failure_reasons" :key="i">{{ reason }}</li>
            </ul>
          </div>
          <div v-if="experienceData.optimization_tips?.length" class="detail-block">
            <div class="detail-block__title">优化建议</div>
            <ul class="detail-block__list">
              <li v-for="(tip, i) in experienceData.optimization_tips" :key="i">{{ tip }}</li>
            </ul>
          </div>
        </template>

        <!-- Pitfall list -->
        <template v-if="drawerType === 'pitfalls'">
          <div v-if="store.pitfalls.length === 0" class="drawer-empty">
            <a-empty description="暂无预警信息" />
          </div>
          <div v-for="(warning, index) in store.pitfalls" :key="index" class="drawer-pitfall-item" @click="openDrawer('pitfall-detail', warning)">
            <a-tag :color="riskColor(warning.risk_level)" size="small">{{ riskLabel(warning.risk_level) }}</a-tag>
            <span>{{ warning.step }}</span>
          </div>
        </template>

        <!-- Pitfall detail -->
        <template v-if="drawerType === 'pitfall-detail' && pitfallData">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="步骤">{{ pitfallData.step }}</a-descriptions-item>
            <a-descriptions-item label="风险等级">
              <a-tag :color="riskColor(pitfallData.risk_level)">{{ riskLabel(pitfallData.risk_level) }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="历史失败率">{{ (pitfallData.historical_failure_rate * 100).toFixed(1) }}%</a-descriptions-item>
          </a-descriptions>
          <div v-if="pitfallData.reason" class="detail-block">
            <div class="detail-block__title">原因</div>
            <div class="detail-block__text">{{ pitfallData.reason }}</div>
          </div>
          <div v-if="pitfallData.suggestion" class="detail-block">
            <div class="detail-block__title">建议</div>
            <div class="detail-block__text">{{ pitfallData.suggestion }}</div>
          </div>
        </template>

        <!-- Usage -->
        <template v-if="drawerType === 'usage'">
          <UsagePanel />
        </template>

        <!-- Metrics -->
        <template v-if="drawerType === 'metrics'">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="总任务数">{{ metrics?.total_tasks ?? 0 }}</a-descriptions-item>
            <a-descriptions-item label="成功率">{{ metrics ? (metrics.success_rate * 100).toFixed(1) : '0.0' }}%</a-descriptions-item>
            <a-descriptions-item label="平均耗时">{{ metrics ? formatDuration(metrics.avg_duration) : '-' }}</a-descriptions-item>
          </a-descriptions>
        </template>

        <!-- Agents -->
        <template v-if="drawerType === 'agents'">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="活跃 Agent 数">{{ activeAgentCount }}</a-descriptions-item>
          </a-descriptions>
          <div v-if="store.experiences.length === 0" class="drawer-empty">
            <a-empty description="暂无 Agent 活动记录" />
          </div>
          <div v-else>
            <div class="detail-block" style="margin-top: var(--space-4)">
              <div class="detail-block__title">按任务类型分布</div>
            </div>
            <div v-for="type in agentTypeStats" :key="type.name" class="drawer-exp-item">
              <div class="drawer-exp-item__body">
                <span class="drawer-exp-item__goal">{{ type.name }}</span>
                <span class="drawer-exp-item__meta">{{ type.count }} 次任务 · 成功率 {{ type.successRate }}%</span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import {
  Card as ACard,
  Statistic as AStatistic,
  Tag as ATag,
  Button as AButton,
  Empty as AEmpty,
  Drawer as ADrawer,
  Descriptions as ADescriptions,
  DescriptionsItem as ADescriptionsItem,
} from 'ant-design-vue'
import {
  CheckCircleOutlined,
  TeamOutlined,
  CloudServerOutlined,
  SafetyCertificateOutlined,
} from '@ant-design/icons-vue'
import { useEvolutionStore } from '@/stores/evolution'
import { evolutionApi } from '@/api/evolution'
import { apiClient } from '@/api/client'
import UsagePanel from './UsagePanel.vue'
import type { Experience, PitfallWarning } from '@/api/evolution'

const store = useEvolutionStore()

const metrics = computed(() => store.metrics)
const recentExperiences = computed(() => store.experiences.slice(0, 5))
const agentTypeStats = computed(() => {
  const typeMap = new Map<string, { total: number; success: number }>()
  for (const exp of store.experiences) {
    const entry = typeMap.get(exp.task_type) || { total: 0, success: 0 }
    entry.total++
    if (exp.outcome === 'success') entry.success++
    typeMap.set(exp.task_type, entry)
  }
  return Array.from(typeMap.entries()).map(([name, { total, success }]) => ({
    name,
    count: total,
    successRate: total > 0 ? ((success / total) * 100).toFixed(1) : '0.0',
  }))
})

const activeAgentCount = ref(0)
const usageSummary = ref({ total_tokens: 0, total_requests: 0 })

// Drawer state
const drawerVisible = ref(false)
const drawerType = ref('')
const drawerData = ref<Experience | PitfallWarning | null>(null)

// Type-narrowed computed for template access without type guards
const experienceData = computed(() =>
  drawerData.value && 'id' in drawerData.value ? drawerData.value as Experience : null
)
const pitfallData = computed(() =>
  drawerData.value && 'step' in drawerData.value ? drawerData.value as PitfallWarning : null
)

const drawerTitleMap: Record<string, string> = {
  tasks: '任务列表',
  experiences: '经验记录',
  'experience-detail': '经验详情',
  pitfalls: '避坑预警',
  'pitfall-detail': '预警详情',
  usage: 'LLM 用量',
  metrics: '质量指标',
  agents: 'Agent 概览',
}

const drawerTitle = computed(() => drawerTitleMap[drawerType.value] || '')

function openDrawer(type: string, data?: Experience | PitfallWarning) {
  drawerType.value = type
  drawerData.value = data || null
  drawerVisible.value = true
}

onMounted(async () => {
  try {
    const usageData = await evolutionApi.getUsage({ period: '7d' })
    usageSummary.value = {
      total_tokens: usageData.summary.total_tokens,
      total_requests: usageData.summary.total_requests,
    }
  } catch {
    // usage endpoint may not be available yet
  }

  // Count distinct task types as proxy for active agents
  if (store.experiences.length > 0) {
    const taskTypes = new Set(store.experiences.map(e => e.task_type))
    activeAgentCount.value = taskTypes.size
  }

  // Use capabilities API as primary source when available, fall back to task-type count
  try {
    const caps = await apiClient.getCapabilities()
    if (caps?.capabilities?.length) {
      // Use capabilities count only if no experience-based count yet
      if (activeAgentCount.value === 0) {
        activeAgentCount.value = caps.capabilities.length
      }
    }
  } catch {
    // capabilities may not be available
  }
})

function formatTime(isoStr: string): string {
  if (!isoStr) return ''
  const d = new Date(isoStr)
  return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
}

function formatDuration(seconds: number): string {
  if (!seconds) return '-'
  if (seconds < 60) return `${seconds.toFixed(1)}秒`
  if (seconds < 3600) return `${(seconds / 60).toFixed(1)}分钟`
  return `${(seconds / 3600).toFixed(1)}小时`
}

function riskColor(level: string): string {
  switch (level) {
    case 'high': return 'red'
    case 'medium': return 'orange'
    case 'low': return 'blue'
    default: return 'default'
  }
}

function riskLabel(level: string): string {
  switch (level) {
    case 'high': return '高'
    case 'medium': return '中'
    case 'low': return '低'
    default: return level
  }
}
</script>

<style scoped>
.dashboard-overview {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

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

.overview-card {
  cursor: pointer;
}

.overview-card__footer {
  font-size: 12px;
  color: var(--text-tertiary);
}

.overview-sections {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  min-height: 0;
}

.overview-section {
  background: var(--bg-primary);
  border: 1px solid var(--border-color-split);
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.overview-section__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-shrink: 0;
}

.overview-section__header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
}

.overview-section__empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.overview-section__list {
  flex: 1;
  overflow-y: auto;
}

.experience-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  border-bottom: 1px solid var(--bg-tertiary);
}

.experience-item:last-child {
  border-bottom: none;
}

.experience-item__dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.experience-item__dot--success {
  background: var(--color-success);
}

.experience-item__dot--failure {
  background: var(--color-error);
}

.experience-item__info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.experience-item__goal {
  font-size: 13px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.experience-item__meta {
  font-size: 12px;
  color: var(--text-tertiary);
}

.pitfall-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  border-bottom: 1px solid var(--bg-tertiary);
}

.pitfall-item:last-child {
  border-bottom: none;
}

.pitfall-item__step {
  flex: 1;
  font-size: 13px;
  font-weight: 500;
}

.pitfall-item__rate {
  font-size: 12px;
  color: var(--color-error);
  font-weight: 600;
}

/* Drawer styles */
.drawer-content {
  padding: var(--space-2) 0;
}

.drawer-empty {
  padding: var(--space-8) 0;
  text-align: center;
}

.drawer-task-item {
  padding: var(--space-3);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-color-split);
  margin-bottom: var(--space-2);
}

.drawer-task-item__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-1);
}

.drawer-task-item__goal {
  font-weight: 500;
  color: var(--text-primary);
}

.drawer-task-item__meta {
  display: flex;
  gap: var(--space-3);
  font-size: 12px;
  color: var(--text-tertiary);
}

.drawer-exp-item {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  padding: var(--space-3);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: background var(--transition-fast);
}

.drawer-exp-item:hover {
  background: var(--bg-tertiary);
}

.drawer-exp-item__dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
  margin-top: 6px;
}

.drawer-exp-item__dot--success { background: var(--color-success); }
.drawer-exp-item__dot--failure { background: var(--color-error); }

.drawer-exp-item__body {
  flex: 1;
  min-width: 0;
}

.drawer-exp-item__header {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.drawer-exp-item__goal {
  font-size: var(--font-sm);
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.drawer-exp-item__meta {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-top: 2px;
}

.drawer-pitfall-item {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  cursor: pointer;
  font-size: var(--font-sm);
  transition: background var(--transition-fast);
}

.drawer-pitfall-item:hover {
  background: var(--bg-tertiary);
}

.detail-block {
  margin-top: var(--space-4);
}

.detail-block__title {
  font-size: var(--font-sm);
  font-weight: 600;
  color: var(--text-secondary);
  margin-bottom: var(--space-1);
}

.detail-block__text {
  font-size: var(--font-sm);
  color: var(--text-tertiary);
  line-height: var(--leading-normal);
}

.detail-block__list {
  margin: 0;
  padding-left: 20px;
  font-size: var(--font-sm);
  color: var(--text-tertiary);
  line-height: var(--leading-normal);
}
</style>
