<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 CRITERION_LABELS = [
  { label: 'Resp rate', key: 'respRate', color: '#3b82f6' },
  { label: 'Systolic BP', key: 'systolicBp', color: '#8b5cf6' },
  { label: 'Altered mentation', key: 'avpu', color: '#ec4899' },
]

function criteriaColor(count) {
  if (count >= 2) return '#dc2626'
  if (count === 1) return '#f59e0b'
  return '#22c55e'
}

function criteriaLabel(count) {
  if (count >= 2) return 'Screen positive (≥2) — consider SOFA labs'
  if (count === 1) return '1 criterion met'
  return 'Screen negative'
}

function criterionMet(value) {
  return value != null ? 1 : 0
}

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

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

  const criterionDatasets = CRITERION_LABELS.map(({ label, key, color }) => ({
    label,
    data: sorted.map(h => criterionMet(h.criteria?.[key])),
    borderColor: color,
    backgroundColor: `${color}33`,
    borderWidth: 1,
    borderDash: [3, 3],
    pointRadius: 0,
    stepped: true,
    yAxisID: 'criteria',
    order: 2,
  }))

  return {
    labels,
    datasets: [
      {
        label: 'Active criteria',
        data: sorted.map(h => h.activeCriteria),
        borderColor: totalLineColor,
        backgroundColor: sorted.map(h => {
          if (h.activeCriteria >= 2) return 'rgba(220, 38, 38, 0.2)'
          if (h.activeCriteria === 1) return 'rgba(245, 158, 11, 0.2)'
          return 'rgba(34, 197, 94, 0.15)'
        }),
        pointBackgroundColor: sorted.map(h => criteriaColor(h.activeCriteria)),
        pointBorderColor: sorted.map(h => criteriaColor(h.activeCriteria)),
        pointRadius: sorted.map(h => (h.screenAlertFired ? 7 : 4)),
        pointStyle: sorted.map(h => (h.screenAlertFired ? 'star' : 'circle')),
        borderWidth: 2,
        fill: true,
        tension: 0.2,
        yAxisID: 'count',
        order: 1,
      },
      ...criterionDatasets,
    ],
  }
})

const chartOptions = computed(() => {
  darkMode.value
  return buildOptions({
    interaction: { mode: 'index', intersect: false },
    scales: {
      count: {
        type: 'linear',
        position: 'left',
        min: 0,
        max: 3,
        ticks: { stepSize: 1 },
        title: { display: true, text: 'Criteria count' },
      },
      criteria: {
        type: 'linear',
        position: 'right',
        min: 0,
        max: 1,
        display: false,
      },
    },
    plugins: {
      legend: {
        display: true,
        position: 'bottom',
      },
      tooltip: {
        callbacks: {
          footer(items) {
            const total = items.find(i => i.dataset.label === 'Active criteria')
            if (!total) return ''
            const idx = total.dataIndex
            const entry = sortedHistory.value[idx]
            const lines = [criteriaLabel(total.parsed.y)]
            if (entry?.screenAlertFired) lines.push('qSOFA screen alert fired')
            return lines.join(' · ')
          },
        },
      },
    },
  }).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">qSOFA Screen Over Time</h3>
    <p class="mb-4 text-xs text-gray-500 dark:text-gray-400">
      Criteria count (0–3); star markers indicate when a screen alert fired.
      <span class="text-green-600 dark:text-green-400">0</span>,
      <span class="text-amber-600 dark:text-amber-400">1</span>,
      <span class="text-red-600 dark:text-red-400">≥2</span>.
    </p>
    <div
      class="aspect-video w-full min-h-[220px] min-w-0 overflow-hidden sm:min-h-0"
      role="img"
      aria-label="qSOFA screening criteria over time chart"
    >
      <Line :data="chartData" :options="chartOptions" />
    </div>
  </div>
</template>
