<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'
import {
  alertSummaryText,
  elevatedContributors,
  formatMedicationContext,
  formatTrendLine,
  hasExplanation,
} from '@/composables/alertExplanation'

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

const CORRELATION_WINDOW_MS = 90 * 60 * 1000

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

const structuredExplanation = computed(() => props.alert.explanation ?? null)
const usesStructuredExplanation = computed(() => hasExplanation(props.alert))
const contributors = computed(() => elevatedContributors(structuredExplanation.value))
const trendLine = computed(() => formatTrendLine(structuredExplanation.value?.trend))
const medicationLine = computed(() =>
  formatMedicationContext(structuredExplanation.value?.medicationContext),
)

const summaryText = computed(() => {
  if (structuredExplanation.value?.narrativeSummary) {
    return structuredExplanation.value.narrativeSummary
  }
  return reasoningMap[props.alert.alertType]?.explain(props.alert)
    ?? alertSummaryText(props.alert)
    ?? ''
})

const recentMedications = computed(() => {
  if (medicationLine.value || !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 = {
    QSOFA_SCREEN: 'Recommend ordering SOFA labs (PaO₂, platelets, bilirubin, creatinine).',
    SOFA_SEPSIS: 'Review organ dysfunction and confirm sepsis bundle initiation.',
    GCS_CRITICAL: 'Urgent neurological assessment — GCS ≤ 8.',
    GCS_WARNING: 'Monitor consciousness closely — GCS 9–12.',
  }
  return hints[props.alert.alertType] ?? null
})

const showTechnicalDetails = computed(() =>
  Boolean(props.alert.details)
  && (!usesStructuredExplanation.value || props.alert.details !== summaryText.value),
)

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">
        {{ summaryText }}
      </p>

      <div
        v-if="contributors.length"
        class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700"
      >
        <table class="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-800/60">
            <tr>
              <th class="px-4 py-2 text-left font-medium text-gray-600 dark:text-gray-300">Parameter</th>
              <th class="px-4 py-2 text-left font-medium text-gray-600 dark:text-gray-300">Points</th>
              <th class="px-4 py-2 text-left font-medium text-gray-600 dark:text-gray-300">Value</th>
              <th class="px-4 py-2 text-left font-medium text-gray-600 dark:text-gray-300">Normal</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
            <tr v-for="(row, index) in contributors" :key="`${row.parameter}-${index}`">
              <td class="px-4 py-2 text-gray-900 dark:text-gray-100">{{ row.parameter }}</td>
              <td class="px-4 py-2 text-gray-700 dark:text-gray-300">{{ row.points }}</td>
              <td class="px-4 py-2 text-gray-700 dark:text-gray-300">{{ row.rawValue ?? '—' }}</td>
              <td class="px-4 py-2 text-gray-500 dark:text-gray-400">{{ row.normalRange ?? '—' }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <p
        v-if="trendLine"
        class="rounded bg-sky-50 px-4 py-2 text-sm text-sky-900 dark:bg-sky-950/40 dark:text-sky-100"
      >
        {{ trendLine }}
      </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="medicationLine"
        class="rounded bg-amber-50 p-4 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200"
      >
        <p class="mb-1 font-medium">Correlated medication</p>
        <p>{{ medicationLine }}</p>
      </div>

      <div
        v-else-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="showTechnicalDetails"
        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>
