<script setup>
import { ref, computed } from 'vue'
import Card from '@/components/ui/Card.vue'
import Badge from '@/components/ui/Badge.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import {
  TIMELINE_EVENT_TYPES,
  formatTimelineEvent,
  timelineEventStyles,
  timelineTypeLabel,
} from '@/composables/timelineFormat'

const props = defineProps({
  events: { type: Array, default: () => [] },
})

const expanded = ref(true)
const sinceHours = ref('')
const enabledTypes = ref(new Set(TIMELINE_EVENT_TYPES.map(t => t.id)))

const hourOptions = [
  { value: '', label: 'All time' },
  { value: '4', label: 'Last 4 hours' },
  { value: '8', label: 'Last 8 hours' },
  { value: '24', label: 'Last 24 hours' },
]

const filteredEvents = computed(() => {
  let list = props.events.filter(e => enabledTypes.value.has(e.type))

  const hours = Number(sinceHours.value)
  if (hours > 0) {
    const cutoff = Date.now() - hours * 60 * 60 * 1000
    list = list.filter(e => new Date(e.timestamp).getTime() >= cutoff)
  }

  return [...list].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
})

function toggleType(typeId) {
  const next = new Set(enabledTypes.value)
  if (next.has(typeId)) next.delete(typeId)
  else next.add(typeId)
  enabledTypes.value = next
}

function formatTime(iso) {
  return new Date(iso).toLocaleString([], {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function alertBadgeVariant(event) {
  if (event.type !== 'alert') return timelineEventStyles(event.type).badge
  return event.severity === 'CRITICAL' ? 'critical' : 'warning'
}
</script>

<template>
  <Card>
    <template #header>
      <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
        <button
          type="button"
          class="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400"
          @click="expanded = !expanded"
        >
          <span class="text-xs" aria-hidden="true">{{ expanded ? '▼' : '▶' }}</span>
          Encounter Timeline
        </button>
        <span v-if="events.length" class="text-xs text-gray-500 dark:text-gray-400">
          {{ filteredEvents.length }} of {{ events.length }} events
        </span>
      </div>
    </template>

    <div v-if="expanded" class="space-y-4">
      <div class="flex flex-wrap items-center gap-3">
        <label class="text-xs text-gray-500 dark:text-gray-400">
          Range
          <select
            v-model="sinceHours"
            class="ml-2 rounded border border-gray-300 bg-white px-2 py-1 text-xs text-gray-800 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-200"
          >
            <option v-for="opt in hourOptions" :key="opt.value" :value="opt.value">
              {{ opt.label }}
            </option>
          </select>
        </label>

        <div class="flex flex-wrap gap-2">
          <button
            v-for="t in TIMELINE_EVENT_TYPES"
            :key="t.id"
            type="button"
            class="rounded-full border px-2 py-0.5 text-xs transition-colors"
            :class="enabledTypes.has(t.id)
              ? 'border-gray-800 bg-gray-800 text-white dark:border-gray-200 dark:bg-gray-200 dark:text-gray-900'
              : 'border-gray-300 text-gray-500 dark:border-gray-600 dark:text-gray-400'"
            @click="toggleType(t.id)"
          >
            {{ t.label }}
          </button>
        </div>
      </div>

      <EmptyState v-if="!filteredEvents.length" message="No timeline events match the current filters" />

      <ol v-else class="relative space-y-0 border-l-2 border-gray-200 pl-4 dark:border-gray-700">
        <li
          v-for="(event, index) in filteredEvents"
          :key="`${event.type}-${event.timestamp}-${index}`"
          class="relative pb-6 last:pb-0"
        >
          <span
            class="absolute -left-[1.3rem] top-1 h-3 w-3 rounded-full ring-2 ring-white dark:ring-gray-900"
            :class="timelineEventStyles(event.type).dot"
          />
          <div
            class="rounded-lg border-l-4 bg-gray-50 p-3 dark:bg-gray-800/50"
            :class="timelineEventStyles(event.type).border"
          >
            <div class="mb-1 flex flex-wrap items-center gap-2">
              <Badge :variant="alertBadgeVariant(event)" size="xs">
                {{ timelineTypeLabel(event.type) }}
              </Badge>
              <time class="text-xs text-gray-500 dark:text-gray-400">
                {{ formatTime(event.timestamp) }}
              </time>
            </div>
            <p class="text-sm text-gray-900 dark:text-gray-100">
              {{ formatTimelineEvent(event) }}
            </p>
          </div>
        </li>
      </ol>
    </div>
  </Card>
</template>
