<script setup>
import { computed } from 'vue'
import { Line } from 'vue-chartjs'
import { Chart as ChartJS, registerables } from 'chart.js'
import { formatTime } from '@/composables/chartFormat'
import { useChartTheme } from '@/composables/useChartTheme'

ChartJS.register(...registerables)

const props = defineProps({ history: { type: Array, required: true } })
const { buildOptions, darkMode, accentLine } = useChartTheme()

const COMPONENT_DATASETS = [
  { label: 'Eye', key: 'eyeScore', color: '#3b82f6' },
  { label: 'Verbal', key: 'verbalScore', color: '#8b5cf6' },
  { label: 'Motor', key: 'motorScore', color: '#06b6d4' },
]

function gcsRiskBorder(score) {
  if (score <= 8) return '#dc2626'
  if (score <= 12) return '#f59e0b'
  return '#22c55e'
}

function gcsSeverityLabel(score) {
  if (score <= 8) return 'Severe (3–8)'
  if (score <= 12) return 'Moderate (9–12)'
  return 'Mild (13–15)'
}

const sortedHistory = computed(() =>
  [...props.history].sort((a, b) => new Date(a.calculatedAt) - new Date(b.calculatedAt)),
)

const chartData = computed(() => {
  const sorted = sortedHistory.value
  const labels = sorted.map(h => formatTime(h.calculatedAt))
  const totalLineColor = accentLine.value

  const componentDatasets = COMPONENT_DATASETS.map(({ label, key, color }) => ({
    label,
    data: sorted.map(h => h[key] ?? 0),
    borderColor: color,
    backgroundColor: 'transparent',
    borderWidth: 1.5,
    borderDash: [4, 3],
    pointRadius: 2,
    tension: 0.2,
    order: 2,
  }))

  return {
    labels,
    datasets: [
      {
        label: 'GCS Total',
        data: sorted.map(h => h.totalScore),
        borderColor: totalLineColor,
        backgroundColor: sorted.map(h => {
          if (h.totalScore <= 8) return 'rgba(220, 38, 38, 0.15)'
          if (h.totalScore <= 12) return 'rgba(245, 158, 11, 0.15)'
          return 'rgba(34, 197, 94, 0.15)'
        }),
        pointBackgroundColor: sorted.map(h => gcsRiskBorder(h.totalScore)),
        pointBorderColor: sorted.map(h => gcsRiskBorder(h.totalScore)),
        pointRadius: 4,
        borderWidth: 2,
        fill: true,
        tension: 0.3,
        order: 1,
      },
      ...componentDatasets,
    ],
  }
})

const chartOptions = computed(() => {
  darkMode.value
  return buildOptions({
    interaction: { mode: 'index', intersect: false },
    scales: {
      y: {
        min: 3,
        max: 15,
        title: { display: true, text: 'GCS Score' },
      },
    },
    plugins: {
      legend: {
        display: true,
        position: 'bottom',
      },
      tooltip: {
        callbacks: {
          footer(items) {
            const total = items.find(i => i.dataset.label === 'GCS Total')
            if (!total) return ''
            return gcsSeverityLabel(total.parsed.y)
          },
        },
      },
    },
  }).value
})
</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-1 text-sm font-medium text-gray-700 dark:text-gray-300">GCS Over Time</h3>
    <p class="mb-4 text-xs text-gray-500 dark:text-gray-400">
      Total score with Eye, Verbal, and Motor components.
      <span class="text-green-600 dark:text-green-400">Mild 13–15</span>,
      <span class="text-amber-600 dark:text-amber-400">Moderate 9–12</span>,
      <span class="text-red-600 dark:text-red-400">Severe 3–8</span>.
    </p>
    <div
      class="aspect-video w-full min-h-[220px] min-w-0 overflow-hidden sm:min-h-0"
      role="img"
      aria-label="Glasgow Coma Scale over time chart"
    >
      <Line :data="chartData" :options="chartOptions" />
    </div>
  </div>
</template>
