<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 auditFilter = ref('')
const severityFilter = ref<'all' | 'high' | 'medium' | 'low'>('all')

const riskFlags = computed(() => store.admin.riskFlags)
const auditEntries = computed(() => store.admin.auditEntries)
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 filteredAuditEntries = computed(() => {
  const query = auditFilter.value.trim().toLowerCase()
  if (!query) return auditEntries.value
  return auditEntries.value.filter((entry) =>
    [entry.summary, entry.adminTwitchUserId, entry.actionType, entry.entityType, entry.entityId]
      .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 & Audit"
      title="Auffällige Muster und Admin-Aktionen verfolgen"
      description="Dieser Bereich trennt operative Risiko-Sichtung von der Nachvollziehbarkeit. So findest du sowohl offene Flags als auch bereits ausgeführte Eingriffe deutlich schneller."
      :icon="ShieldAlert"
    />

    <div class="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
      <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">
        <div class="flex items-center justify-between gap-4">
          <div>
            <h2 class="font-[Cormorant_Garamond] text-4xl text-violet-800">Audit-Protokoll</h2>
            <p class="mt-2 text-sm text-slate-500">Nachvollziehbare Admin-Aktionen für Kategorie-, Kandidaten- und Review-Änderungen.</p>
          </div>
          <span class="text-sm uppercase tracking-[0.2em] text-slate-500">
            {{ filteredAuditEntries.length }} / {{ auditEntries.length }} Einträge
          </span>
        </div>

        <div class="mt-6">
          <input
            v-model="auditFilter"
            type="text"
            class="w-full rounded-2xl border border-violet-200 px-4 py-3"
            placeholder="Audit-Einträge nach Aktion, Admin oder Objekt filtern"
          />
        </div>

        <div class="mt-6 space-y-4">
          <div
            v-for="entry in filteredAuditEntries"
            :key="entry.id"
            class="rounded-[26px] border border-violet-100 bg-violet-50/60 px-5 py-5"
          >
            <div class="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p class="font-semibold text-slate-800">{{ entry.summary }}</p>
                <p class="mt-1 text-sm text-slate-500">
                  {{ entry.adminTwitchUserId }} · {{ entry.actionType }} · {{ entry.entityType }} {{ entry.entityId }}
                </p>
              </div>
              <p class="text-sm text-slate-500">{{ new Date(entry.createdAt).toLocaleString('de-DE') }}</p>
            </div>
          </div>

          <p v-if="auditEntries.length === 0" class="rounded-[26px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
            Noch keine Audit-Einträge vorhanden.
          </p>
          <p v-else-if="filteredAuditEntries.length === 0" class="rounded-[26px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
            Keine Audit-Einträge passen zum aktuellen Filter.
          </p>
        </div>
      </Card>
    </div>
  </div>
</template>
