<template>
  <div class="metrics-chart">
    <div class="chart-header">
      <h3>指标趋势</h3>
      <div class="period-selector">
        <a-radio-group v-model:value="selectedPeriod" size="small" @change="onPeriodChange">
          <a-radio-button value="7d">7天</a-radio-button>
          <a-radio-button value="30d">30天</a-radio-button>
          <a-radio-button value="all">全部</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    <div v-if="trends.length === 0" class="chart-empty">
      <a-empty description="暂无趋势数据" />
    </div>
    <div v-else class="chart-body">
      <!-- Summary cards -->
      <div class="summary-row">
        <div class="summary-card">
          <div class="summary-label">成功率</div>
          <div class="summary-value" style="color: #10b981">
            {{ metrics ? (metrics.success_rate * 100).toFixed(1) + '%' : '-' }}
          </div>
        </div>
        <div class="summary-card">
          <div class="summary-label">平均耗时</div>
          <div class="summary-value" style="color: #7c3aed">
            {{ metrics ? formatDuration(metrics.avg_duration) : '-' }}
          </div>
        </div>
        <div class="summary-card">
          <div class="summary-label">重试率</div>
          <div class="summary-value" style="color: #f59e0b">
            {{ metrics ? (metrics.retry_rate * 100).toFixed(1) + '%' : '-' }}
          </div>
        </div>
      </div>
      <!-- ECharts container -->
      <div ref="chartRef" class="echarts-container"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { RadioGroup as ARadioGroup, RadioButton as ARadioButton, Empty as AEmpty } from 'ant-design-vue'
import echarts from '@/utils/echarts'
import type { EvolutionMetrics, TrendPoint } from '@/api/evolution'

const props = defineProps<{
  metrics: EvolutionMetrics | null
  trends: TrendPoint[]
  period: string
}>()

const emit = defineEmits<{
  (e: 'period-change', period: string): void
}>()

const selectedPeriod = ref(props.period)
const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null
let resizeObserver: ResizeObserver | null = null

function onPeriodChange() {
  emit('period-change', selectedPeriod.value)
}

// Sync selectedPeriod with prop changes
watch(() => props.period, (val) => {
  selectedPeriod.value = val
})

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

function initChart() {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

function updateChart() {
  if (!chartInstance || !props.trends.length) return

  const dates = props.trends.map(t => t.date.slice(5))

  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
    },
    legend: {
      data: ['成功率', '重试率', '平均耗时'],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      top: '8%',
      bottom: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
    },
    yAxis: [
      {
        type: 'value',
        name: '比率',
        axisLabel: { formatter: '{value}%' },
        min: 0,
        max: 100,
      },
      {
        type: 'value',
        name: '耗时(ms)',
        axisLabel: { formatter: '{value}' },
      },
    ],
    series: [
      {
        name: '成功率',
        type: 'line',
        data: props.trends.map(t => +(t.success_rate * 100).toFixed(1)),
        smooth: true,
        itemStyle: { color: '#10b981' },
        symbol: 'circle',
        symbolSize: 6,
      },
      {
        name: '重试率',
        type: 'line',
        data: props.trends.map(t => +(t.retry_rate * 100).toFixed(1)),
        smooth: true,
        itemStyle: { color: '#f59e0b' },
        symbol: 'circle',
        symbolSize: 6,
      },
      {
        name: '平均耗时',
        type: 'line',
        yAxisIndex: 1,
        data: props.trends.map(t => +(t.avg_duration).toFixed(0)),
        smooth: true,
        itemStyle: { color: '#7c3aed' },
        lineStyle: { type: 'dashed' },
        symbol: 'circle',
        symbolSize: 6,
      },
    ],
  }, true)
}

onMounted(() => {
  if (props.trends.length > 0) {
    initChart()
  }
  if (chartRef.value) {
    resizeObserver = new ResizeObserver(() => {
      if (chartInstance) chartInstance.resize()
    })
    resizeObserver.observe(chartRef.value)
  }
})

onUnmounted(() => {
  chartInstance?.dispose()
  chartInstance = null
  resizeObserver?.disconnect()
})

// When trends transition from empty to non-empty, init chart after DOM update
watch(() => props.trends, (newTrends) => {
  if (newTrends.length > 0 && !chartInstance) {
    nextTick(() => initChart())
  }
}, { deep: true })

watch(() => [props.trends, props.period], updateChart, { deep: true })
</script>

<style scoped>
.metrics-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.chart-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
}

.chart-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.summary-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.summary-card {
  flex: 1;
  background: var(--bg-secondary);
  border-radius: 6px;
  padding: 8px 12px;
  text-align: center;
}

.summary-label {
  font-size: 12px;
  color: var(--text-tertiary);
  margin-bottom: 2px;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
}

.chart-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.echarts-container {
  flex: 1;
  min-height: 200px;
}
</style>
