<script setup>
import { computed, shallowRef, markRaw } from 'vue'
import { Line } from 'vue-chartjs'
import { Chart, registerables } from 'chart.js'
import { alertTypeLabel } from '@/api/normalize'

Chart.register(...registerables)

const props = defineProps({
  snapshots: { type: Array, required: true },
  metric: {
    type: String,
    default: 'usefulRate',
    validator: v => ['usefulRate', 'falsePositiveRate', 'acknowledgementRate', 'wouldActRate'].includes(v),
  },
  title: { type: String, default: 'Alert Quality Over Time' },
})

const METRIC_LABELS = {
  usefulRate: 'Useful Rate %',
  falsePositiveRate: 'False Positive Rate %',
  acknowledgementRate: 'Acknowledgement Rate %',
  wouldActRate: 'Would Act Rate %',
}

const chartData = computed(() => {
  const sorted = [...props.snapshots].sort(
    (a, b) => new Date(a.windowStart) - new Date(b.windowStart),
  )
  return {
    labels: sorted.map(s => alertTypeLabel(s.alertType)),
    datasets: [{
      label: METRIC_LABELS[props.metric],
      data: sorted.map(s => Math.round(s[props.metric] * 100)),
      borderColor: '#3b82f6',
      backgroundColor: 'rgba(59, 130, 246, 0.15)',
      fill: true,
      tension: 0.3,
      pointRadius: 4,
    }],
  }
})

const chartOptions = shallowRef(markRaw({
  responsive: true,
  maintainAspectRatio: true,
  animation: {
    duration: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 400,
  },
  scales: {
    y: { min: 0, max: 100, title: { display: true, text: '%' } },
  },
  plugins: { legend: { display: false } },
}))
</script>

<template>
  <div class="w-full min-w-0 rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-900">
    <h3 class="mb-4 text-sm font-medium text-gray-700 dark:text-gray-300">{{ title }}</h3>
    <div class="aspect-video w-full min-h-0 overflow-hidden">
      <Line v-if="snapshots.length" :data="chartData" :options="chartOptions" />
      <p v-else class="text-sm text-gray-400">No metrics for this period yet.</p>
    </div>
  </div>
</template>