<script setup lang="ts">
import { computed, ref } from '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 riskFlags = computed(() => store.admin.riskFlags)
const auditEntries = computed(() => store.admin.auditEntries)
const filteredRiskFlags = computed(() => {
  const query = riskFilter.value.trim().toLowerCase()
  if (!query) return riskFlags.value
  return riskFlags.value.filter((flag) =>
    [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),
  )
})

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="Auffaellige Muster und Admin-Aktionen verfolgen"
      description="Dieser Bereich trennt operative Risiko-Sichtung von der Nachvollziehbarkeit. So findest du sowohl offene Flags als auch bereits ausgefuehrte Eingriffe deutlich schneller."
    />

    <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">Risikopruefung</h2>
            <p class="mt-2 text-sm text-slate-500">Auffaellige Login-, Nominierungs- und Voting-Muster fuer die manuelle Sichtung.</p>
          </div>
          <span class="text-sm uppercase tracking-[0.2em] text-slate-500">
            {{ filteredRiskFlags.length }} / {{ riskFlags.length }} offen
          </span>
        </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]">
          <input
            v-model="riskFilter"
            type="text"
            class="rounded-2xl border border-violet-200 px-4 py-3"
            placeholder="Risikohinweise nach Typ, Nutzer oder IP filtern"
          />
          <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 geprueften Fall.
          </div>
        </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 fuer Kategorie-, Kandidaten- und Review-Aenderungen.</p>
          </div>
          <span class="text-sm uppercase tracking-[0.2em] text-slate-500">
            {{ filteredAuditEntries.length }} / {{ auditEntries.length }} Eintraege
          </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-Eintraege 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-Eintraege 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-Eintraege passen zum aktuellen Filter.
          </p>
        </div>
      </Card>
    </div>
  </div>
</template>
