<script setup lang="ts">
import { computed, ref } from 'vue'
import { Search, ShieldAlert } from '@lucide/vue'

import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import Button from '../../components/ui/Button.vue'
import Card from '../../components/ui/Card.vue'
import { useAwardsStore } from '../../stores/awards'

const store = useAwardsStore()
const riskSaving = ref<number | null>(null)
const adminMessage = ref('')
const adminError = ref('')
const riskFilter = ref('')
const severityFilter = ref<'all' | 'high' | 'medium' | 'low'>('all')

const riskFlags = computed(() => store.admin.riskFlags)
const filteredRiskFlags = computed(() => {
  const query = riskFilter.value.trim().toLowerCase()
  return riskFlags.value.filter((flag) =>
    (severityFilter.value === 'all' || flag.severity.toLowerCase() === severityFilter.value) &&
    (!query || [flag.source, flag.type, flag.summary, flag.twitchUserId ?? '', flag.createdFromIp]
      .join(' ')
      .toLowerCase()
      .includes(query)),
  )
})
const riskStats = computed(() => [
  { label: 'Offen', value: riskFlags.value.length },
  { label: 'High', value: riskFlags.value.filter((flag) => flag.severity.toLowerCase() === 'high').length },
  { label: 'User betroffen', value: new Set(riskFlags.value.map((flag) => flag.twitchUserId).filter(Boolean)).size },
])
const severityFilters = computed(() => [
  { key: 'all' as const, label: 'Alle', count: riskFlags.value.length },
  { key: 'high' as const, label: 'High', count: riskFlags.value.filter((flag) => flag.severity.toLowerCase() === 'high').length },
  { key: 'medium' as const, label: 'Medium', count: riskFlags.value.filter((flag) => flag.severity.toLowerCase() === 'medium').length },
  { key: 'low' as const, label: 'Low', count: riskFlags.value.filter((flag) => flag.severity.toLowerCase() === 'low').length },
])

async function resolveRiskFlag(riskFlagId: number, status = 'resolved') {
  riskSaving.value = riskFlagId
  adminMessage.value = ''
  adminError.value = ''

  try {
    await store.resolveRiskFlag(riskFlagId, status)
    adminMessage.value = `Risikohinweis ${riskFlagId} wurde aktualisiert.`
  } catch (error) {
    adminError.value = error instanceof Error ? error.message : 'Risikohinweis konnte nicht aktualisiert werden.'
  } finally {
    riskSaving.value = null
  }
}
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Risiko"
      title="Auffällige Muster entscheiden"
      description="Dieser Bereich ist nur für operative Risiko-Sichtung zuständig: Voting-, Login- und Einreichungsmuster prüfen, verwerfen oder erledigt markieren. Audit-Logs liegen separat im Team-Audit."
      :icon="ShieldAlert"
    />

    <div class="grid gap-6 xl:grid-cols-[0.82fr_1.18fr]">
      <Card class="p-7">
        <div class="flex items-center justify-between gap-4">
          <div>
            <h2 class="font-[Cormorant_Garamond] text-4xl text-violet-800">Risikoprüfung</h2>
            <p class="mt-2 text-sm text-slate-500">Auffällige Login-, Nominierungs- und Voting-Muster für die manuelle Sichtung.</p>
          </div>
          <span class="text-sm uppercase tracking-[0.2em] text-slate-500">
            {{ filteredRiskFlags.length }} / {{ riskFlags.length }} offen
          </span>
        </div>
        <div class="mt-5 grid gap-2 sm:grid-cols-3">
          <div v-for="stat in riskStats" :key="stat.label" class="rounded-2xl border border-violet-50 bg-violet-50/50 px-3 py-2">
            <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">{{ stat.label }}</p>
            <strong class="mt-1 block text-lg text-violet-800">{{ stat.value }}</strong>
          </div>
        </div>

        <p v-if="adminMessage" class="mt-6 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
          {{ adminMessage }}
        </p>
        <p v-if="adminError" class="mt-6 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
          {{ adminError }}
        </p>

        <div class="mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_220px]">
          <label class="relative block">
            <Search class="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-violet-400" />
            <input
              v-model="riskFilter"
              type="text"
              class="h-12 w-full rounded-2xl border border-violet-200 bg-white pl-11 pr-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
              placeholder="Typ, Nutzer oder IP filtern"
            />
          </label>
          <div class="rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm text-slate-600">
            Tipp: Filtere erst auf den Problemtyp und markiere dann nur den geprüften Fall.
          </div>
        </div>
        <div class="mt-3 flex flex-wrap gap-2">
          <button
            v-for="filter in severityFilters"
            :key="filter.key"
            type="button"
            class="rounded-full border px-3 py-1.5 text-xs font-semibold transition"
            :class="severityFilter === filter.key ? 'border-violet-200 bg-violet-100 text-violet-800' : 'border-violet-100 bg-white text-slate-600 hover:bg-violet-50'"
            @click="severityFilter = filter.key"
          >
            {{ filter.label }} · {{ filter.count }}
          </button>
        </div>

        <div class="mt-6 space-y-4">
          <div
            v-for="flag in filteredRiskFlags"
            :key="flag.id"
            class="rounded-[26px] border border-violet-100 bg-white/90 p-5"
          >
            <div class="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">{{ flag.source }} · {{ flag.type }}</p>
                <h3 class="mt-2 font-[Cormorant_Garamond] text-3xl text-violet-800">{{ flag.summary }}</h3>
                <p class="mt-2 text-sm text-slate-500">
                  {{ flag.twitchUserId || 'unbekannter User' }} · {{ flag.createdFromIp }} · {{ new Date(flag.createdAt).toLocaleString('de-DE') }}
                </p>
              </div>
              <div class="rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm font-semibold uppercase tracking-[0.2em] text-slate-600">
                {{ flag.severity }}
              </div>
            </div>

            <pre class="mt-4 overflow-x-auto rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-xs text-slate-600">{{ flag.metadataJson }}</pre>

            <div class="mt-4 flex flex-wrap justify-end gap-3">
              <Button :disabled="riskSaving === flag.id" variant="secondary" @click="resolveRiskFlag(flag.id, 'dismissed')">
                {{ riskSaving === flag.id ? 'Speichert ...' : 'Verwerfen' }}
              </Button>
              <Button :disabled="riskSaving === flag.id" @click="resolveRiskFlag(flag.id, 'resolved')">
                {{ riskSaving === flag.id ? 'Speichert ...' : 'Erledigt markieren' }}
              </Button>
            </div>
          </div>

          <p v-if="riskFlags.length === 0" class="rounded-[26px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
            Keine offenen Risikohinweise vorhanden.
          </p>
          <p v-else-if="filteredRiskFlags.length === 0" class="rounded-[26px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
            Keine Risikohinweise passen zum aktuellen Filter.
          </p>
        </div>
      </Card>

      <Card class="p-7">
        <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Review-Protokoll</p>
        <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Risk Playbook</h2>
        <div class="mt-6 space-y-3">
          <div class="rounded-[22px] border border-violet-100 bg-white/90 p-4">
            <p class="font-semibold text-slate-900">1. Quelle prüfen</p>
            <p class="mt-1 text-sm leading-6 text-slate-500">Vote-Flags vor Ergebnisfreigabe priorisieren, Clip-Flags vor Public-Einbindung, Login-Flags bei wiederholten IP-Mustern.</p>
          </div>
          <div class="rounded-[22px] border border-violet-100 bg-white/90 p-4">
            <p class="font-semibold text-slate-900">2. Entscheidung dokumentieren</p>
            <p class="mt-1 text-sm leading-6 text-slate-500">„Erledigt“ bedeutet geprüft und relevant; „Verwerfen“ bedeutet false positive oder kein Award-Risiko.</p>
          </div>
          <div class="rounded-[22px] border border-violet-100 bg-white/90 p-4">
            <p class="font-semibold text-slate-900">3. Audit separat lesen</p>
            <p class="mt-1 text-sm leading-6 text-slate-500">Admin-Aktionen findest du im Team-Audit, damit Risikoentscheidungen nicht mit normalen Bearbeitungen vermischt werden.</p>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>
