import { onBeforeUnmount } from 'vue'
import { useWardStore } from '@/stores/ward'
import { useSettingsStore } from '@/stores/settings'
import { alertTypeLabel } from '@/api/normalize'
import { alertSummaryText } from '@/composables/alertExplanation'

const DEFAULT_TITLE = 'VigilCare'
let titleFlashTimer = null
let titleFlashOriginal = DEFAULT_TITLE

export function playCriticalTone() {
  try {
    const ctx = new AudioContext()
    const playBeep = (startTime) => {
      const oscillator = ctx.createOscillator()
      const gain = ctx.createGain()
      oscillator.type = 'square'
      oscillator.frequency.value = 880
      gain.gain.setValueAtTime(0.12, startTime)
      gain.gain.exponentialRampToValueAtTime(0.001, startTime + 0.35)
      oscillator.connect(gain)
      gain.connect(ctx.destination)
      oscillator.start(startTime)
      oscillator.stop(startTime + 0.35)
    }
    playBeep(ctx.currentTime)
    playBeep(ctx.currentTime + 0.45)
    window.setTimeout(() => ctx.close(), 1000)
  } catch {
    // Autoplay may be blocked until user interaction.
  }
}

export function flashCriticalTitle() {
  if (titleFlashTimer) return

  titleFlashOriginal = document.title || DEFAULT_TITLE
  let showAlert = true
  titleFlashTimer = window.setInterval(() => {
    document.title = showAlert ? '⚠ CRITICAL ALERT — VigilCare' : titleFlashOriginal
    showAlert = !showAlert
  }, 1000)
}

export function stopCriticalTitleFlash() {
  if (titleFlashTimer) {
    clearInterval(titleFlashTimer)
    titleFlashTimer = null
  }
  if (document.title.includes('CRITICAL ALERT')) {
    document.title = titleFlashOriginal || DEFAULT_TITLE
  }
}

export async function requestNotificationPermission() {
  if (!('Notification' in window)) return 'unsupported'
  if (Notification.permission === 'granted') return 'granted'
  if (Notification.permission === 'denied') return 'denied'
  return Notification.requestPermission()
}

export function formatAlertPatientLabel(alert) {
  const wardStore = useWardStore()
  const encounter = wardStore.encounters.find(
    item => item.encounterId === alert.encounterId,
  )
  if (encounter) {
    return `${encounter.firstName} ${encounter.lastName} (${encounter.mrn})`
  }

  const patient = alert.encounter?.patient
  if (patient?.firstName || patient?.lastName) {
    const mrn = patient.mrn ? ` (${patient.mrn})` : ''
    return `${patient.firstName ?? ''} ${patient.lastName ?? ''}${mrn}`.trim()
  }

  return alert.details ?? 'Critical patient alert'
}

export function showBrowserNotification(alert) {
  if (!('Notification' in window) || Notification.permission !== 'granted') return

  const patientLabel = formatAlertPatientLabel(alert)
  const body = alertSummaryText(alert)
    ? `${patientLabel} — ${alertSummaryText(alert)}`
    : patientLabel

  new Notification(`Critical: ${alertTypeLabel(alert.alertType)}`, {
    body,
    tag: alert.id,
  })
}

export function useAlertNotification() {
  const settings = useSettingsStore()

  function notifyNewCriticalAlerts(alerts) {
    if (alerts.length === 0) return

    if (!settings.alertSoundMuted) {
      playCriticalTone()
    }
    flashCriticalTitle()

    for (const alert of alerts) {
      showBrowserNotification(alert)
    }
  }

  onBeforeUnmount(stopCriticalTitleFlash)

  return {
    notifyNewCriticalAlerts,
    requestNotificationPermission,
    stopCriticalTitleFlash,
    playCriticalTone,
  }
}
