<script setup>
import { computed } from 'vue'
import Badge from '@/components/ui/Badge.vue'
import Card from '@/components/ui/Card.vue'
import FeedbackButtons from '@/components/feedback/FeedbackButtons.vue'

const props = defineProps({
  alert: { type: Object, required: true },
  medications: { type: Array, default: () => [] },
})

const CORRELATION_WINDOW_MS = 90 * 60 * 1000

const reasoningMap = {
  WarningHeartRate: {
    label: 'Heart Rate Warning',
    explain: (a) => `Heart rate ${extractValue(a)} is in the warning range (91–110 bpm or 41–50 bpm).`,
  },
  WarningSystolicBp: {
    label: 'Systolic BP Warning',
    explain: (a) => `Systolic BP ${extractValue(a)} is in the warning range (101–110 mmHg).`,
  },
  WarningTempC: {
    label: 'Temperature Warning',
    explain: (a) => `Temperature ${extractValue(a)} is in the warning range.`,
  },
  SepsisWarning: {
    label: 'SIRS / Sepsis Alert (Legacy)',
    explain: () =>
      'Historical alert: ≥2 of 4 SIRS criteria met. New sepsis detection uses SOFA delta ≥ 2.',
  },
  QsofaWarning: {
    label: 'qSOFA Alert (Legacy)',
    explain: () => 'Historical alert: ≥2 of 3 qSOFA criteria met.',
  },
  QsofaScreen: {
    label: 'qSOFA Screen',
    explain: () =>
      'Bedside screen positive (≥2/3). Recommend ordering SOFA labs to evaluate organ dysfunction.',
  },
  SofaSepsis: {
    label: 'Sepsis Alert (SOFA)',
    explain: (a) => explainSofaAlert(a, true),
  },
  SofaWarning: {
    label: 'SOFA Warning',
    explain: (a) => explainSofaAlert(a, false),
  },
  GcsCritical: {
    label: 'GCS Critical',
    explain: (a) => explainGcsAlert(a),
  },
  GcsWarning: {
    label: 'GCS Warning',
    explain: (a) => explainGcsAlert(a),
  },
  News2Warning: {
    label: 'NEWS2 Medium Risk',
    explain: () => 'NEWS2 composite score 5–6 indicating medium clinical risk.',
  },
  News2Emergency: {
    label: 'NEWS2 High Risk',
    explain: () => 'NEWS2 composite score ≥7 or any single parameter scored 3.',
  },
  RapidDeterioration: {
    label: 'Rapid Deterioration',
    explain: () => 'Vital sign trajectory shows rapid change within the sliding window.',
  },
}

const recentMedications = computed(() => {
  if (!props.medications.length || !props.alert.triggeredAt) return []
  const alertTime = new Date(props.alert.triggeredAt).getTime()
  return props.medications.filter(m => {
    const administeredAt = new Date(m.administeredAt).getTime()
    const delta = alertTime - administeredAt
    return delta >= 0 && delta <= CORRELATION_WINDOW_MS
  })
})

const actionHint = computed(() => {
  const hints = {
    QsofaScreen: 'Recommend ordering SOFA labs (PaO₂, platelets, bilirubin, creatinine).',
    SofaSepsis: 'Review organ dysfunction and confirm sepsis bundle initiation.',
    GcsCritical: 'Urgent neurological assessment — GCS ≤ 8.',
    GcsWarning: 'Monitor consciousness closely — GCS 9–12.',
  }
  return hints[props.alert.alertType] ?? null
})

function extractValue(alert) {
  const match = alert.details?.match(/(\d+\.?\d*)/)
  return match ? match[1] : '—'
}

function explainGcsAlert(alert) {
  const e = alert.details?.match(/E[=:]?\s*(\d)/i)?.[1]
  const v = alert.details?.match(/V[=:]?\s*(\d)/i)?.[1]
  const m = alert.details?.match(/M[=:]?\s*(\d)/i)?.[1]
  if (e && v && m) return `GCS components: Eye ${e}, Verbal ${v}, Motor ${m}.`
  return alert.details ?? 'GCS threshold crossed.'
}

function explainSofaAlert(alert, isSepsis) {
  const delta = alert.details?.match(/delta\s*[+:]?\s*(\d+)/i)?.[1]
  const baseline = alert.details?.match(/baseline\s*(\d+)/i)?.[1]
  const current = alert.details?.match(/current\s*(\d+)/i)?.[1]
  const parts = []
  if (baseline && current && delta) {
    parts.push(`SOFA score increased from ${baseline} to ${current} (delta +${delta}).`)
  } else if (delta) {
    parts.push(`SOFA delta +${delta} from baseline.`)
  }
  const organs = alert.details?.match(/organs?:\s*([^.]+)/i)?.[1]
  if (organs) parts.push(`Organ dysfunction: ${organs.trim()}.`)
  if (isSepsis) parts.push('Meets sepsis criteria: suspected infection + SOFA delta ≥ 2.')
  return parts.length ? parts.join(' ') : (alert.details ?? 'SOFA threshold crossed.')
}

function formatMed(med) {
  return `${med.drugName} ${med.dose}${med.doseUnit} (${med.route})`
}
</script>

<template>
  <Card>
    <div class="space-y-4">
      <div class="flex flex-wrap items-center gap-2">
        <Badge :variant="alert.severity === 'Critical' ? 'critical' : 'warning'">
          {{ alert.severity }}
        </Badge>
        <h3 class="font-medium dark:text-white">
          {{ reasoningMap[alert.alertType]?.label ?? alert.alertType }}
        </h3>
      </div>

      <p class="text-sm text-gray-600 dark:text-gray-400">
        {{ reasoningMap[alert.alertType]?.explain(alert) ?? alert.details }}
      </p>

      <p
        v-if="actionHint"
        class="rounded bg-blue-50 px-4 py-2 text-sm text-blue-800 dark:bg-blue-950/40 dark:text-blue-200"
      >
        {{ actionHint }}
      </p>

      <div
        v-if="recentMedications.length"
        class="rounded bg-amber-50 p-4 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200"
      >
        <p class="mb-2 font-medium">Recent medications (within 90 min)</p>
        <ul class="space-y-2">
          <li v-for="med in recentMedications" :key="med.id">
            {{ formatMed(med) }} — {{ new Date(med.administeredAt).toLocaleString() }}
          </li>
        </ul>
      </div>

      <div
        v-if="alert.details"
        class="rounded bg-gray-50 p-4 text-xs font-mono text-gray-700 dark:bg-gray-800 dark:text-gray-300"
      >
        {{ alert.details }}
      </div>

      <div class="text-xs text-gray-500 dark:text-gray-500">
        Triggered at {{ new Date(alert.triggeredAt).toLocaleString() }}
      </div>

      <div class="border-t border-gray-100 pt-4 dark:border-gray-700">
        <FeedbackButtons
          :alert-id="alert.id"
          :alert-type="alert.alertType"
          :severity="alert.severity"
        />
      </div>
    </div>
  </Card>
</template>