<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/api'

const loading = ref(true)
const incidents = ref<any[]>([])
const categories = ref<any[]>([])
const showModal = ref(false)
const form = ref({ title: '', description: '', category_id: '', severity: 2, object_id: '' })

onMounted(async () => {
  await loadData()
})

async function loadData() {
  loading.value = true
  try {
    const [incRes, catRes] = await Promise.all([
      api.get<any>('/incidents'),
      api.get<any>('/incidents/categories')
    ])
    incidents.value = incRes.data.incidents || []
    categories.value = catRes.data.categories || []
  } catch (e) { console.error(e) }
  loading.value = false
}

async function createIncident() {
  try {
    await api.post('/incidents', form.value)
    showModal.value = false
    form.value = { title: '', description: '', category_id: '', severity: 2, object_id: '' }
    await loadData()
  } catch (e: any) { alert('Fehler: ' + e.message) }
}

function severityColor(s: number): string {
  if (s >= 4) return 'bg-red-100 text-red-700'
  if (s >= 3) return 'bg-orange-100 text-orange-700'
  return 'bg-yellow-100 text-yellow-700'
}

function statusBadge(s: string): { text: string, class: string } {
  const map: Record<string, any> = {
    open: { text: 'Offen', class: 'bg-red-100 text-red-700' },
    in_progress: { text: 'In Bearbeitung', class: 'bg-yellow-100 text-yellow-700' },
    resolved: { text: 'Gelöst', class: 'bg-green-100 text-green-700' },
    closed: { text: 'Geschlossen', class: 'bg-gray-100 text-gray-700' }
  }
  return map[s] || { text: s, class: 'bg-gray-100' }
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold">🚨 Vorfallberichte</h1>
        <p class="text-gray-500">Incidents dokumentieren und verfolgen</p>
      </div>
      <button @click="showModal = true" class="btn btn-primary">+ Vorfall melden</button>
    </div>

    <div v-if="loading" class="text-center py-12">Laden...</div>

    <div v-else-if="incidents.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
      <p class="text-4xl mb-4">✅</p>
      <p>Keine Vorfälle gemeldet</p>
    </div>

    <div v-else class="space-y-4">
      <div v-for="inc in incidents" :key="inc.id" class="bg-white rounded-lg shadow p-4">
        <div class="flex justify-between items-start">
          <div class="flex items-start space-x-3">
            <span class="text-2xl">{{ inc.category_icon || '📋' }}</span>
            <div>
              <h3 class="font-semibold">{{ inc.title }}</h3>
              <p class="text-sm text-gray-500">{{ inc.category_name }} · {{ inc.object_name || 'Ohne Objekt' }}</p>
              <p class="text-sm text-gray-400 mt-1">{{ new Date(inc.occurred_at).toLocaleString('de-DE') }}</p>
            </div>
          </div>
          <div class="flex flex-col items-end space-y-1">
            <span :class="['px-2 py-1 text-xs rounded', statusBadge(inc.status).class]">
              {{ statusBadge(inc.status).text }}
            </span>
            <span :class="['px-2 py-1 text-xs rounded', severityColor(inc.severity)]">
              Stufe {{ inc.severity }}
            </span>
          </div>
        </div>
        <p v-if="inc.description" class="mt-3 text-sm text-gray-600">{{ inc.description }}</p>
        <div class="mt-3 flex items-center text-xs text-gray-500">
          <span>Gemeldet von {{ inc.reporter_first }} {{ inc.reporter_last }}</span>
          <span v-if="inc.attachment_count" class="ml-4">📎 {{ inc.attachment_count }} Anhänge</span>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div v-if="showModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-lg p-6">
        <h2 class="text-xl font-bold mb-4">Vorfall melden</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Titel *</label>
            <input v-model="form.title" class="input" placeholder="Kurze Beschreibung" />
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Kategorie</label>
            <select v-model="form.category_id" class="input">
              <option value="">-- Wählen --</option>
              <option v-for="c in categories" :key="c.id" :value="c.id">{{ c.icon }} {{ c.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Schweregrad (1-5)</label>
            <input v-model.number="form.severity" type="range" min="1" max="5" class="w-full" />
            <div class="flex justify-between text-xs text-gray-500">
              <span>Gering</span><span>Kritisch</span>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Beschreibung</label>
            <textarea v-model="form.description" rows="3" class="input" placeholder="Details..."></textarea>
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-6">
          <button @click="showModal = false" class="btn">Abbrechen</button>
          <button @click="createIncident" class="btn btn-primary">Melden</button>
        </div>
      </div>
    </div>
  </div>
</template>
