<template>
  <div class="p-4 sm:p-6 max-w-5xl mx-auto">

    <!-- Header -->
    <div class="mb-6">
      <h1 class="text-text-primary text-xl font-semibold mb-1">Incidents</h1>
      <p class="text-text-dim text-sm">
        Tagged incidents and their log evidence.
        <RouterLink
          to="/diagnose?tab=structured"
          class="text-accent hover:text-blue-300 underline underline-offset-2 ml-1"
        >Tag a new incident →</RouterLink>
      </p>
    </div>

    <!-- Incidents table -->
    <div v-if="loading" class="text-text-dim py-8 text-center text-sm">Loading…</div>

    <div v-else-if="incidents.length === 0" class="text-text-dim py-12 text-center text-sm">
      No incidents tagged yet.
    </div>

    <div v-else class="rounded border border-surface-border overflow-hidden">
      <div class="overflow-x-auto">
      <table class="w-full text-sm min-w-[600px]">
        <thead class="bg-surface-raised border-b border-surface-border">
          <tr>
            <th class="text-left px-4 py-2.5 text-text-dim font-medium text-xs uppercase tracking-wider">Description</th>
            <th class="text-left px-4 py-2.5 text-text-dim font-medium text-xs uppercase tracking-wider">Type</th>
            <th class="text-left px-4 py-2.5 text-text-dim font-medium text-xs uppercase tracking-wider">Severity</th>
            <th class="text-left px-4 py-2.5 text-text-dim font-medium text-xs uppercase tracking-wider">Window</th>
            <th class="text-left px-4 py-2.5 text-text-dim font-medium text-xs uppercase tracking-wider">Tagged</th>
            <th class="px-4 py-2.5"></th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="inc in incidents"
            :key="inc.id"
            class="border-b border-surface-border hover:bg-surface-raised transition-colors cursor-pointer"
            @click="selectIncident(inc)"
          >
            <td class="px-4 py-2.5 text-text-primary">{{ inc.label }}</td>
            <td class="px-4 py-2.5">
              <span v-if="inc.issue_type" class="font-mono text-xs text-accent bg-surface px-1.5 py-0.5 rounded border border-surface-border">{{ inc.issue_type }}</span>
              <span v-else class="text-text-dim text-xs">—</span>
            </td>
            <td class="px-4 py-2.5">
              <span class="px-2 py-0.5 rounded text-xs font-medium border" :style="severityStyle(inc.severity)">
                {{ inc.severity }}
              </span>
            </td>
            <td class="px-4 py-2.5 text-text-dim text-xs">{{ windowLabel(inc) }}</td>
            <td class="px-4 py-2.5 text-text-dim text-xs">{{ formatTs(inc.created_at) }}</td>
            <td class="px-4 py-2.5 text-right">
              <button
                @click.stop="deleteIncident(inc.id)"
                class="text-text-dim hover:text-sev-error transition-colors text-xs px-2 py-1 rounded hover:bg-surface"
              >
                delete
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      </div>
    </div>

    <!-- Incident detail drawer -->
    <div v-if="selected" class="mt-6 rounded border border-accent bg-surface p-5">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-text-primary text-sm font-semibold">{{ selected.label }}</h2>
          <span v-if="selected.issue_type" class="font-mono text-xs text-accent">{{ selected.issue_type }}</span>
        </div>
        <div class="flex flex-wrap items-center gap-2 sm:gap-3 mt-1 sm:mt-0">
          <label class="flex items-center gap-1.5 text-xs text-text-dim cursor-pointer select-none">
            <input type="checkbox" v-model="sanitizeBundle" class="accent-accent" />
            Sanitize PII
          </label>
          <button
            @click="sendBundle(selected.id)"
            :disabled="sending"
            class="px-3 py-1.5 text-xs rounded border border-surface-border text-text-muted hover:text-accent hover:border-accent transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
          >
            {{ sending ? 'Sending…' : 'Send Bundle' }}
          </button>
          <span v-if="sendStatus" :class="sendStatus.ok ? 'text-green-500' : 'text-sev-error'" class="text-xs">{{ sendStatus.msg }}</span>
          <button @click="selected = null" class="text-text-dim hover:text-text-primary text-xs ml-auto sm:ml-0">✕ close</button>
        </div>
      </div>

      <!-- Incident metadata: severity + notes -->
      <div class="flex flex-wrap gap-x-6 gap-y-2 text-sm mb-4 pb-4 border-b border-surface-border">
        <div class="flex items-center gap-2">
          <span class="text-xs text-text-dim">Severity</span>
          <span class="px-2 py-0.5 rounded text-xs font-medium border" :style="severityStyle(selected.severity)">
            {{ selected.severity || 'medium' }}
          </span>
        </div>
        <div v-if="selected.notes" class="flex items-start gap-2 min-w-0">
          <span class="text-xs text-text-dim shrink-0 mt-0.5">Notes</span>
          <span class="text-sm text-text-primary break-words">{{ selected.notes }}</span>
        </div>
        <div class="flex items-center gap-2 text-xs text-text-dim">
          <span>Window</span>
          <span>{{ windowLabel(selected) }}</span>
        </div>
      </div>

      <div v-if="entriesLoading" class="text-text-dim text-sm py-4">Fetching log entries…</div>

      <div v-else-if="selectedEntries.length === 0" class="text-text-dim text-sm py-4">
        No log entries found in this window.
      </div>

      <div v-else>
        <!-- Timeline visualizer -->
        <IncidentTimeline
          class="mb-4"
          :entries="selectedEntries"
          :started-at="selected.started_at"
          :ended-at="selected.ended_at"
          @select-entry="scrollToEntry"
        />

        <div
          id="incident-entries"
          class="space-y-1 max-h-96 overflow-y-auto"
        >
          <div
            v-for="(entry, idx) in selectedEntries"
            :key="entry.entry_id"
            :id="`incident-entry-${idx}`"
            class="font-mono text-xs py-1 px-2 rounded bg-surface-raised border border-surface-border transition-colors"
            :class="{ 'ring-1 ring-accent': highlightIdx === idx }"
          >
            <span class="text-text-dim mr-2">{{ shortTs(entry.timestamp_iso) }}</span>
            <span :class="['mr-2', severityTextClass(entry.severity)]">{{ entry.severity || '?' }}</span>
            <span class="text-text-muted">{{ entry.source_id.split(':').pop() }}</span>
            <span class="text-text-dim mx-1">|</span>
            <span class="text-text-primary">{{ entry.text.slice(0, 200) }}</span>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import IncidentTimeline from '@/components/IncidentTimeline.vue'

const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')

interface Incident {
  id: string
  label: string
  issue_type: string
  started_at: string | null
  ended_at: string | null
  notes: string
  created_at: string
  severity: string
}

interface Entry {
  entry_id: string
  source_id: string
  timestamp_iso: string | null
  severity: string | null
  text: string
}

// ── list + delete ────────────────────────────────────────────
const incidents = ref<Incident[]>([])
const loading   = ref(true)

onMounted(async () => {
  try {
    const res = await fetch(`${BASE}/api/incidents`)
    if (res.ok) incidents.value = (await res.json()).incidents
  } finally {
    loading.value = false
  }
})

async function deleteIncident(id: string) {
  await fetch(`${BASE}/api/incidents/${id}`, { method: 'DELETE' })
  incidents.value = incidents.value.filter(i => i.id !== id)
  if (selected.value?.id === id) selected.value = null
}

// ── detail drawer ─────────────────────────────────────────────
const selected        = ref<Incident | null>(null)
const selectedEntries = ref<Entry[]>([])
const entriesLoading  = ref(false)
const sending         = ref(false)
const sendStatus      = ref<{ ok: boolean; msg: string } | null>(null)
const sanitizeBundle  = ref(false)

async function selectIncident(inc: Incident) {
  selected.value = inc
  selectedEntries.value = []
  entriesLoading.value = true
  sendStatus.value = null
  try {
    const res = await fetch(`${BASE}/api/incidents/${inc.id}`)
    if (res.ok) {
      const data = await res.json()
      selectedEntries.value = data.entries ?? []
    }
  } finally {
    entriesLoading.value = false
  }
}

async function sendBundle(id: string) {
  sending.value = true
  sendStatus.value = null
  try {
    const params = sanitizeBundle.value ? '?sanitize=true' : ''
    const res = await fetch(`${BASE}/api/incidents/${id}/send${params}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      const tag = sanitizeBundle.value ? ' (sanitized)' : ''
      sendStatus.value = { ok: true, msg: `Sent ${data.entry_count} entries${tag}` }
    } else {
      const err = await res.json().catch(() => ({ detail: res.statusText }))
      sendStatus.value = { ok: false, msg: err.detail ?? 'Send failed' }
    }
  } catch {
    sendStatus.value = { ok: false, msg: 'Network error' }
  } finally {
    sending.value = false
  }
}

// ── timeline interaction ──────────────────────────────────────
const highlightIdx = ref<number | null>(null)

function scrollToEntry(idx: number) {
  highlightIdx.value = idx
  const el = document.getElementById(`incident-entry-${idx}`)
  el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
  setTimeout(() => { highlightIdx.value = null }, 1500)
}

// ── helpers ───────────────────────────────────────────────────
function severityStyle(sev: string): Record<string, string> {
  const k = sev?.toLowerCase() ?? 'low'
  const known = ['low', 'medium', 'high', 'critical']
  const key = known.includes(k) ? k : 'low'
  return {
    backgroundColor: `var(--badge-${key}-bg)`,
    color:           `var(--badge-${key}-text)`,
    borderColor:     `var(--badge-${key}-text)`,
  }
}

function severityTextClass(sev: string | null): string {
  return {
    ERROR:    'text-sev-error',
    CRITICAL: 'text-sev-critical',
    WARN:     'text-sev-warn',
    WARNING:  'text-sev-warn',
    INFO:     'text-sev-info',
    DEBUG:    'text-text-dim',
  }[sev?.toUpperCase() ?? ''] ?? 'text-text-dim'
}

function windowLabel(inc: Incident): string {
  if (!inc.started_at && !inc.ended_at) return '—'
  const s = inc.started_at ? formatTs(inc.started_at) : '—'
  const e = inc.ended_at   ? formatTs(inc.ended_at)   : 'ongoing'
  return `${s} → ${e}`
}

function formatTs(iso: string | null): string {
  if (!iso) return '—'
  try {
    return new Date(iso).toLocaleString(undefined, {
      month: 'short', day: 'numeric',
      hour: '2-digit', minute: '2-digit',
    })
  } catch { return iso }
}

function shortTs(iso: string | null): string {
  if (!iso) return '?'
  try {
    return new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })
  } catch { return iso }
}
</script>
