<template>
  <div class="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">Tag time windows with descriptions. The label is used to search for related log entries.</p>
    </div>

    <!-- Create form -->
    <div class="mb-8 rounded border border-surface-border bg-surface-raised p-5">
      <h2 class="text-text-primary text-sm font-semibold mb-4 uppercase tracking-wider">Tag New Incident</h2>

      <div class="space-y-4">

        <!-- Label -->
        <div>
          <label class="block text-xs text-text-dim mb-1">Description <span class="text-accent">*</span></label>
          <input
            v-model="form.label"
            type="text"
            placeholder='e.g. "plex stopped playing audio" or "bluetooth kept disconnecting"'
            class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
          />
          <p class="text-text-dim text-xs mt-1">Your literal description — used to find relevant log entries in the window.</p>
        </div>

        <!-- Time bucket picker -->
        <div>
          <label class="block text-xs text-text-dim mb-2">When did it happen?</label>
          <div class="flex flex-wrap gap-2 mb-3">
            <button
              v-for="preset in presets"
              :key="preset.key"
              @click="applyPreset(preset.key)"
              :class="[
                'px-3 py-1.5 rounded text-xs border transition-colors',
                activePreset === preset.key
                  ? 'bg-accent text-surface border-accent'
                  : 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
              ]"
            >
              {{ preset.label }}
            </button>
            <button
              @click="toggleCustomPicker"
              :class="[
                'px-3 py-1.5 rounded text-xs border transition-colors',
                showCustomPicker
                  ? 'bg-accent text-surface border-accent'
                  : 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
              ]"
            >
              Custom range…
            </button>
          </div>

          <!-- Custom date range picker -->
          <div v-if="showCustomPicker" class="flex flex-wrap gap-3 mt-2">
            <div>
              <label class="block text-xs text-text-dim mb-1">Start</label>
              <input
                v-model="form.started_at_local"
                type="datetime-local"
                class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
                @change="activePreset = 'custom'"
              />
            </div>
            <div>
              <label class="block text-xs text-text-dim mb-1">End <span class="text-text-dim">(leave blank if ongoing)</span></label>
              <input
                v-model="form.ended_at_local"
                type="datetime-local"
                class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
                @change="activePreset = 'custom'"
              />
            </div>
          </div>

          <!-- Active window summary -->
          <p v-if="windowSummary" class="text-text-dim text-xs mt-2">
            Window: <span class="text-text-muted">{{ windowSummary }}</span>
          </p>
        </div>

        <!-- Issue type -->
        <div>
          <label class="block text-xs text-text-dim mb-1">Issue type <span class="text-text-dim">(optional — short tag for pattern building)</span></label>
          <input
            v-model="form.issue_type"
            type="text"
            list="issue-type-suggestions"
            placeholder='e.g. "qbit_stall", "auth_failure", "disk_full"'
            class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent font-mono"
          />
          <datalist id="issue-type-suggestions">
            <option value="qbit_stall" />
            <option value="qbit_crash" />
            <option value="auth_failure" />
            <option value="disk_full" />
            <option value="network_drop" />
            <option value="service_crash" />
            <option value="permission_error" />
            <option value="oom" />
          </datalist>
        </div>

        <!-- Severity + Notes row -->
        <div class="flex flex-wrap gap-4">
          <div>
            <label class="block text-xs text-text-dim mb-1">Severity</label>
            <select
              v-model="form.severity"
              class="bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary focus:outline-none focus:border-accent"
            >
              <option value="low">Low</option>
              <option value="medium">Medium</option>
              <option value="high">High</option>
              <option value="critical">Critical</option>
            </select>
          </div>
          <div class="flex-1 min-w-48">
            <label class="block text-xs text-text-dim mb-1">Notes <span class="text-text-dim">(optional)</span></label>
            <input
              v-model="form.notes"
              type="text"
              placeholder="Any extra context…"
              class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
            />
          </div>
        </div>

        <!-- Submit -->
        <div class="flex items-center gap-3">
          <button
            @click="submitIncident"
            :disabled="!form.label.trim() || submitting"
            class="px-4 py-2 bg-accent text-surface text-sm rounded font-medium hover:opacity-90 transition-opacity disabled:opacity-40 disabled:cursor-not-allowed"
          >
            {{ submitting ? 'Tagging…' : 'Tag Incident' }}
          </button>
          <span v-if="submitError" class="text-sev-error text-xs">{{ submitError }}</span>
        </div>
      </div>
    </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. Use the form above to mark your first one.
    </div>

    <div v-else class="rounded border border-surface-border overflow-hidden">
      <table class="w-full text-sm">
        <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>

    <!-- 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 items-center gap-3">
          <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">✕ close</button>
        </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>
        <p class="text-text-dim text-xs mb-3">{{ selectedEntries.length }} entries in window</p>
        <div class="space-y-1 max-h-96 overflow-y-auto">
          <div
            v-for="entry in selectedEntries"
            :key="entry.entry_id"
            class="font-mono text-xs py-1 px-2 rounded bg-surface-raised border border-surface-border"
          >
            <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, computed, onMounted } from '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
}

const presets = [
  { key: 'ongoing',  label: 'Ongoing' },
  { key: 'just_now', label: 'Just now' },
  { key: 'last_1h',  label: 'Last hour' },
  { key: 'last_day', label: 'Last day' },
]

function getQuickRange(preset: string): { started_at: string | null; ended_at: string | null } {
  const now = new Date()
  const iso = (d: Date) => d.toISOString()

  if (preset === 'ongoing') {
    return { started_at: iso(now), ended_at: null }
  }
  const offsets: Record<string, number> = {
    just_now: 15 * 60 * 1000,
    last_1h:  60 * 60 * 1000,
    last_day: 24 * 60 * 60 * 1000,
  }
  const ms = offsets[preset]
  return ms !== undefined
    ? { started_at: iso(new Date(now.getTime() - ms)), ended_at: iso(now) }
    : { started_at: null, ended_at: null }
}

// ── form state ──────────────────────────────────────────────
const form = ref({
  label: '',
  issue_type: '',
  severity: 'medium',
  notes: '',
  started_at: null as string | null,
  ended_at: null as string | null,
  started_at_local: '',
  ended_at_local: '',
})

const activePreset   = ref<string | null>(null)
const showCustomPicker = ref(false)
const submitting     = ref(false)
const submitError    = ref('')

function applyPreset(key: string) {
  activePreset.value = key
  showCustomPicker.value = false
  const range = getQuickRange(key)
  form.value.started_at = range.started_at
  form.value.ended_at   = range.ended_at
}

function toggleCustomPicker() {
  showCustomPicker.value = !showCustomPicker.value
  if (showCustomPicker.value) activePreset.value = 'custom'
}

const windowSummary = computed(() => {
  const start = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
  const end   = showCustomPicker.value ? localToIso(form.value.ended_at_local)   : form.value.ended_at
  if (!start && !end) return ''
  const s = start ? formatTs(start) : '—'
  const e = end   ? formatTs(end)   : 'ongoing'
  return `${s} → ${e}`
})

function localToIso(local: string): string | null {
  if (!local) return null
  return new Date(local).toISOString()
}

async function submitIncident() {
  submitError.value = ''
  if (!form.value.label.trim()) return

  const started_at = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
  const ended_at   = showCustomPicker.value ? localToIso(form.value.ended_at_local)   : form.value.ended_at

  submitting.value = true
  try {
    const res = await fetch(`${BASE}/api/incidents`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        label:      form.value.label,
        issue_type: form.value.issue_type,
        severity:   form.value.severity,
        notes:      form.value.notes,
        started_at,
        ended_at,
      }),
    })
    if (!res.ok) throw new Error(await res.text())
    const created: Incident = await res.json()
    incidents.value.unshift(created)
    form.value = { label: '', issue_type: '', severity: 'medium', notes: '', started_at: null, ended_at: null, started_at_local: '', ended_at_local: '' }
    activePreset.value = null
    showCustomPicker.value = false
  } catch (e: unknown) {
    submitError.value = e instanceof Error ? e.message : 'Failed to create incident'
  } finally {
    submitting.value = false
  }
}

// ── 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)

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 res = await fetch(`${BASE}/api/incidents/${id}/send`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      sendStatus.value = { ok: true, msg: `Sent ${data.entry_count} entries` }
    } else {
      const err = await res.json().catch(() => ({ detail: res.statusText }))
      sendStatus.value = { ok: false, msg: err.detail ?? 'Send failed' }
    }
  } catch (e) {
    sendStatus.value = { ok: false, msg: 'Network error' }
  } finally {
    sending.value = false
  }
}

// ── 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>
