<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: #52c41a">
            {{ metrics ? (metrics.success_rate * 100).toFixed(1) + '%' : '-' }}
          </div>
        </div>
        <div class="summary-card">
          <div class="summary-label">平均耗时</div>
          <div class="summary-value" style="color: #1890ff">
            {{ metrics ? formatDuration(metrics.avg_duration) : '-' }}
          </div>
        </div>
        <div class="summary-card">
          <div class="summary-label">重试率</div>
          <div class="summary-value" style="color: #fa8c16">
            {{ metrics ? (metrics.retry_rate * 100).toFixed(1) + '%' : '-' }}
          </div>
        </div>
      </div>
      <!-- SVG Chart -->
      <div class="svg-chart-container">
        <svg :width="chartWidth" :height="chartHeight" class="svg-chart">
          <!-- Grid lines -->
          <line
            v-for="i in 5"
            :key="'grid-' + i"
            :x1="chartPadding.left"
            :y1="chartPadding.top + (chartHeight - chartPadding.top - chartPadding.bottom) * (i - 1) / 4"
            :x2="chartWidth - chartPadding.right"
            :y2="chartPadding.top + (chartHeight - chartPadding.top - chartPadding.bottom) * (i - 1) / 4"
            stroke="#f0f0f0"
            stroke-width="1"
          />
          <!-- Y-axis labels -->
          <text
            v-for="i in 5"
            :key="'ylabel-' + i"
            :x="chartPadding.left - 8"
            :y="chartPadding.top + (chartHeight - chartPadding.top - chartPadding.bottom) * (i - 1) / 4 + 4"
            text-anchor="end"
            font-size="10"
            fill="#8c8c8c"
          >
            {{ ((5 - i) * 25) }}%
          </text>
          <!-- Success rate line -->
          <polyline
            :points="successRatePoints"
            fill="none"
            stroke="#52c41a"
            stroke-width="2"
            stroke-linejoin="round"
          />
          <!-- Avg duration line (normalized) -->
          <polyline
            :points="avgDurationPoints"
            fill="none"
            stroke="#1890ff"
            stroke-width="2"
            stroke-linejoin="round"
            stroke-dasharray="4,2"
          />
          <!-- Retry rate line -->
          <polyline
            :points="retryRatePoints"
            fill="none"
            stroke="#fa8c16"
            stroke-width="2"
            stroke-linejoin="round"
          />
          <!-- Data points for success rate -->
          <circle
            v-for="(pt, i) in successRateCoords"
            :key="'sr-' + i"
            :cx="pt.x"
            :cy="pt.y"
            r="3"
            fill="#52c41a"
          />
          <!-- X-axis date labels (show every Nth) -->
          <text
            v-for="(pt, i) in xLabelCoords"
            :key="'xlabel-' + i"
            :x="pt.x"
            :y="chartHeight - 4"
            text-anchor="middle"
            font-size="10"
            fill="#8c8c8c"
          >
            {{ pt.label }}
          </text>
        </svg>
        <!-- Legend -->
        <div class="chart-legend">
          <span class="legend-item"><span class="legend-dot" style="background: #52c41a" />成功率</span>
          <span class="legend-item"><span class="legend-dot" style="background: #1890ff" />平均耗时(归一化)</span>
          <span class="legend-item"><span class="legend-dot" style="background: #fa8c16" />重试率</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { RadioGroup as ARadioGroup, RadioButton as ARadioButton, Empty as AEmpty } from 'ant-design-vue'
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 chartWidth = 400
const chartHeight = 220
const chartPadding = { top: 20, right: 16, bottom: 30, left: 40 }

const plotWidth = computed(() => chartWidth - chartPadding.left - chartPadding.right)
const plotHeight = computed(() => chartHeight - chartPadding.top - chartPadding.bottom)

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

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 toX(index: number, total: number): number {
  if (total <= 1) return chartPadding.left + plotWidth.value / 2
  return chartPadding.left + (index / (total - 1)) * plotWidth.value
}

function toY(value: number): number {
  // value is 0..1 range
  const clamped = Math.max(0, Math.min(1, value))
  return chartPadding.top + plotHeight.value * (1 - clamped)
}

const successRateCoords = computed(() => {
  return props.trends.map((t, i) => ({
    x: toX(i, props.trends.length),
    y: toY(t.success_rate),
  }))
})

const avgDurationCoords = computed(() => {
  // Normalize avg_duration to 0..1 range
  const maxDuration = Math.max(...props.trends.map(t => t.avg_duration), 1)
  return props.trends.map((t, i) => ({
    x: toX(i, props.trends.length),
    y: toY(t.avg_duration / maxDuration),
  }))
})

const retryRateCoords = computed(() => {
  return props.trends.map((t, i) => ({
    x: toX(i, props.trends.length),
    y: toY(t.retry_rate),
  }))
})

const successRatePoints = computed(() =>
  successRateCoords.value.map(p => `${p.x},${p.y}`).join(' ')
)

const avgDurationPoints = computed(() =>
  avgDurationCoords.value.map(p => `${p.x},${p.y}`).join(' ')
)

const retryRatePoints = computed(() =>
  retryRateCoords.value.map(p => `${p.x},${p.y}`).join(' ')
)

const xLabelCoords = computed(() => {
  const total = props.trends.length
  // Show every Nth label depending on total points
  const step = total <= 7 ? 1 : total <= 14 ? 2 : Math.ceil(total / 7)
  return props.trends
    .map((t, i) => ({ x: toX(i, total), label: t.date.slice(5), index: i }))
    .filter((_, i) => i % step === 0 || i === total - 1)
})
</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: #fafafa;
  border-radius: 6px;
  padding: 8px 12px;
  text-align: center;
}

.summary-label {
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 2px;
}

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

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

.svg-chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.svg-chart {
  max-width: 100%;
}

.chart-legend {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 8px;
  font-size: 12px;
  color: #8c8c8c;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}
</style>
