<script setup lang="ts">
import { computed } from 'vue'
import { ArrowDownRight, ArrowUpRight, BarChart3, Clock3, LayoutDashboard, ShieldAlert, Sparkles, Tags, Users } from '@lucide/vue'
import { RouterLink } from 'vue-router'

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

const store = useAwardsStore()

const metrics = computed(() => store.admin.metrics)
const activities = computed(() => store.admin.activities)
const topCategories = computed(() => store.admin.topCategories)
const metricToneMap = {
  Nominierungen: {
    icon: Sparkles,
    trend: 12.4,
    sparkline: [42, 48, 53, 51, 59, 64, 71],
    context: 'Nominierungsdruck steigt',
  },
  Stimmen: {
    icon: BarChart3,
    trend: 8.7,
    sparkline: [54, 57, 63, 66, 72, 76, 81],
    context: 'Voting-Aktivität stabil positiv',
  },
  Kategorien: {
    icon: Tags,
    trend: 0,
    sparkline: [62, 62, 62, 63, 63, 63, 63],
    context: 'Struktur bleibt konstant',
  },
  'Reviews offen': {
    icon: Clock3,
    trend: -6.2,
    sparkline: [82, 78, 75, 73, 68, 65, 61],
    context: 'Backlog wird kleiner',
  },
}
const metricCards = computed(() =>
  metrics.value.map((metric) => ({
    ...metric,
    ...(metricToneMap[metric.label as keyof typeof metricToneMap] ?? {
      icon: BarChart3,
      trend: 0,
      sparkline: [50, 50, 50, 50, 50, 50, 50],
      context: metric.note,
    }),
  })),
)
const maxCategoryVotes = computed(() => Math.max(...topCategories.value.map((category) => category.votes), 1))
const totalCategoryVotes = computed(() => topCategories.value.reduce((sum, category) => sum + category.votes, 0))
const yearTotals = computed(() => [
  {
    label: 'Nominierungen gesamt',
    value: metrics.value.find((metric) => metric.label === 'Nominierungen')?.value ?? 0,
    note: `im Award-Jahr ${store.adminSeasonDetail.year}`,
    icon: Sparkles,
  },
  {
    label: 'Stimmen gesamt',
    value: metrics.value.find((metric) => metric.label === 'Stimmen')?.value ?? 0,
    note: 'alle abgegebenen Votes',
    icon: BarChart3,
  },
  {
    label: 'Kandidaten',
    value: store.adminSeasonDetail.candidates.length,
    note: 'für Voting und Archiv gepflegt',
    icon: Users,
  },
  {
    label: 'Kategorien',
    value: store.adminSeasonDetail.categories.length,
    note: 'aktive Award-Kategorien',
    icon: Tags,
  },
  {
    label: 'Offene Reviews',
    value: store.adminSeasonDetail.pendingNominations.length,
    note: 'brauchen Team-Entscheidung',
    icon: Clock3,
  },
  {
    label: 'Risikohinweise',
    value: store.admin.riskFlags.length,
    note: 'aktuell offen',
    icon: ShieldAlert,
  },
])
const priorityActions = computed(() => [
  {
    label: 'Reviews bearbeiten',
    value: store.adminSeasonDetail.pendingNominations.length,
    to: '/admin/reviews',
    hint: 'Freitext-Nominierungen warten auf Entscheidung',
    icon: Sparkles,
    tone: 'violet',
  },
  {
    label: 'Risiko prüfen',
    value: store.admin.riskFlags.length,
    to: '/admin/risk',
    hint: 'Auffällige Muster brauchen Sichtung',
    icon: ShieldAlert,
    tone: 'rose',
  },
  {
    label: 'Kategorien pflegen',
    value: store.adminSeasonDetail.categories.length,
    to: '/admin/categories',
    hint: 'Texte, Limits und Reihenfolge aktuell halten',
    icon: Tags,
    tone: 'amber',
  },
  {
    label: 'Kandidatenbasis',
    value: store.adminSeasonDetail.candidates.length,
    to: '/admin/candidates',
    hint: 'Kandidaten und Plattformen schnell prüfen',
    icon: Users,
    tone: 'emerald',
  },
])
const operationChecks = computed(() => {
  const categoriesWithoutCandidates = store.adminSeasonDetail.categories.filter((category) =>
    !store.adminSeasonDetail.candidates.some((candidate) => candidate.categoryId === category.id),
  )
  const categoriesWithReviews = store.adminSeasonDetail.categories.filter((category) =>
    store.adminSeasonDetail.pendingNominations.some((nomination) => nomination.categoryId === category.id),
  )

  return [
    {
      label: 'Kategorien ohne Kandidaten',
      value: categoriesWithoutCandidates.length,
      to: '/admin/categories',
      state: categoriesWithoutCandidates.length === 0 ? 'ok' : 'warn',
      note: categoriesWithoutCandidates.length === 0 ? 'Alle Kategorien sind besetzt.' : 'Vor Voting-Endspurt prüfen.',
    },
    {
      label: 'Review-Backlog verteilt',
      value: categoriesWithReviews.length,
      to: '/admin/nominations',
      state: categoriesWithReviews.length <= 1 ? 'ok' : 'warn',
      note: categoriesWithReviews.length <= 1 ? 'Backlog ist fokussiert.' : 'Mehrere Kategorien brauchen Sichtung.',
    },
    {
      label: 'Risk Flags offen',
      value: store.admin.riskFlags.length,
      to: '/admin/risk',
      state: store.admin.riskFlags.length === 0 ? 'ok' : 'danger',
      note: store.admin.riskFlags.length === 0 ? 'Keine offenen Hinweise.' : 'Missbrauchsschutz zuerst prüfen.',
    },
  ]
})
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Dashboard"
      title="Was braucht gerade Aufmerksamkeit?"
      description="Trends, offene Aufgaben und Kategorie-Performance sind hier gebündelt, damit du schneller entscheiden kannst, was als Nächstes drankommt."
      :icon="LayoutDashboard"
    />

    <section class="grid gap-4 xl:grid-cols-[1.15fr_0.85fr]">
      <Card class="overflow-hidden">
        <div class="border-b border-violet-100 bg-gradient-to-br from-white via-violet-50/70 to-amber-50/60 p-6">
          <div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.28em] text-violet-500">Live-Lage</p>
              <h2 class="mt-2 font-[Cormorant_Garamond] text-5xl leading-none text-violet-800">Community Momentum</h2>
              <p class="mt-3 max-w-2xl text-sm leading-6 text-slate-600">
                Voting und Nominierungen ziehen an, während der Review-Backlog sinkt. Gute Lage, aber Risikohinweise bleiben priorisiert.
              </p>
            </div>
            <div class="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
              +9.8% Gesamtaktivität
            </div>
          </div>
        </div>

        <div class="grid gap-4 p-5 md:grid-cols-2">
          <div
            v-for="metric in metricCards"
            :key="metric.label"
            class="rounded-[24px] border border-violet-100 bg-white/90 p-5 shadow-[0_16px_42px_rgba(168,145,214,0.08)]"
          >
            <div class="flex items-start justify-between gap-3">
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">{{ metric.label }}</p>
                <strong class="mt-3 block text-4xl text-violet-900">{{ metric.value.toLocaleString('de-DE') }}</strong>
              </div>
              <div class="grid h-10 w-10 place-items-center rounded-2xl bg-violet-100 text-violet-700">
                <component :is="metric.icon" class="h-5 w-5" />
              </div>
            </div>

            <div class="mt-4 flex items-center justify-between gap-3">
              <span
                class="inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-semibold"
                :class="metric.trend < 0 ? 'bg-emerald-50 text-emerald-700' : metric.trend > 0 ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-600'"
              >
                <ArrowDownRight v-if="metric.trend < 0" class="h-3.5 w-3.5" />
                <ArrowUpRight v-else-if="metric.trend > 0" class="h-3.5 w-3.5" />
                {{ metric.trend === 0 ? 'stabil' : `${metric.trend > 0 ? '+' : ''}${metric.trend}%` }}
              </span>
              <span class="text-xs text-slate-500">{{ metric.context }}</span>
            </div>

            <div class="mt-5 flex h-16 items-end gap-1.5">
              <span
                v-for="(value, index) in metric.sparkline"
                :key="`${metric.label}-${index}`"
                class="flex-1 rounded-t-full bg-gradient-to-t from-[#7c5cff] to-[#c4b5fd]"
                :style="{ height: `${value}%` }"
              />
            </div>
          </div>
        </div>
      </Card>

      <Card class="p-6">
        <div class="flex items-center justify-between gap-4">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.26em] text-violet-500">Schnellzugriffe</p>
            <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Was zuerst?</h2>
          </div>
          <Clock3 class="h-6 w-6 text-amber-500" />
        </div>

        <div class="mt-5 space-y-3">
          <RouterLink
            v-for="item in priorityActions"
            :key="item.label"
            :to="item.to"
            class="group block rounded-[22px] border border-violet-100 bg-white/85 p-4 transition hover:-translate-y-0.5 hover:border-violet-200 hover:bg-violet-50/70"
          >
            <div class="flex items-center justify-between gap-4">
              <div class="flex min-w-0 items-center gap-3">
                <div
                  class="grid h-10 w-10 shrink-0 place-items-center rounded-2xl"
                  :class="{
                    'bg-violet-100 text-violet-700': item.tone === 'violet',
                    'bg-rose-100 text-rose-700': item.tone === 'rose',
                    'bg-amber-100 text-amber-700': item.tone === 'amber',
                    'bg-emerald-100 text-emerald-700': item.tone === 'emerald',
                  }"
                >
                  <component :is="item.icon" class="h-5 w-5" />
                </div>
                <div class="min-w-0">
                  <p class="truncate font-semibold text-slate-800">{{ item.label }}</p>
                  <p class="truncate text-sm text-slate-500">{{ item.hint }}</p>
                </div>
              </div>
              <strong class="rounded-full border border-violet-100 bg-white px-3 py-1 text-violet-800">{{ item.value }}</strong>
            </div>
          </RouterLink>
        </div>
      </Card>
    </section>

    <section class="grid gap-4 lg:grid-cols-3">
      <RouterLink
        v-for="check in operationChecks"
        :key="check.label"
        :to="check.to"
        class="rounded-[24px] border bg-white/85 p-5 shadow-[0_16px_42px_rgba(168,145,214,0.08)] transition hover:-translate-y-0.5 hover:bg-violet-50/50"
        :class="{
          'border-emerald-100': check.state === 'ok',
          'border-amber-100': check.state === 'warn',
          'border-rose-100': check.state === 'danger',
        }"
      >
        <div class="flex items-start justify-between gap-4">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">{{ check.label }}</p>
            <strong class="mt-3 block text-3xl" :class="check.state === 'danger' ? 'text-rose-700' : check.state === 'warn' ? 'text-amber-700' : 'text-emerald-700'">
              {{ check.value }}
            </strong>
            <p class="mt-2 text-sm leading-5 text-slate-500">{{ check.note }}</p>
          </div>
        </div>
      </RouterLink>
    </section>

    <section class="grid gap-6 xl:grid-cols-[0.92fr_1.08fr]">
      <Card class="p-7">
        <div class="flex items-center justify-between gap-4">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.26em] text-violet-500">Jahreszahlen</p>
            <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Gesamtmetriken {{ store.adminSeasonDetail.year }}</h2>
          </div>
          <BarChart3 class="h-6 w-6 text-amber-500" />
        </div>

        <div class="mt-6 grid gap-3 sm:grid-cols-2">
          <div
            v-for="item in yearTotals"
            :key="item.label"
            class="rounded-[22px] border border-violet-100 bg-white/90 p-4"
          >
            <div class="flex items-start justify-between gap-3">
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">{{ item.label }}</p>
                <strong class="mt-2 block text-3xl text-violet-900">{{ item.value.toLocaleString('de-DE') }}</strong>
              </div>
              <div class="grid h-9 w-9 place-items-center rounded-2xl bg-violet-100 text-violet-700">
                <component :is="item.icon" class="h-4 w-4" />
              </div>
            </div>
            <p class="mt-3 text-sm leading-5 text-slate-500">{{ item.note }}</p>
          </div>
        </div>
      </Card>

      <Card class="p-7">
        <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.26em] text-violet-500">Kategorie-Performance</p>
            <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Top Kategorien nach Stimmen</h2>
          </div>
          <p class="text-sm text-slate-500">{{ totalCategoryVotes.toLocaleString('de-DE') }} Stimmen in den Top-Kategorien</p>
        </div>

        <div class="mt-6 space-y-4">
          <div
            v-for="(category, index) in topCategories"
            :key="category.category"
            class="rounded-[24px] border border-violet-100 bg-white/90 p-4"
          >
            <div class="flex items-center justify-between gap-4">
              <div>
                <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">#{{ index + 1 }}</p>
                <h3 class="mt-1 font-semibold text-slate-800">{{ category.category }}</h3>
              </div>
              <strong class="text-lg text-violet-800">{{ Number(category.votes).toLocaleString('de-DE') }}</strong>
            </div>
            <div class="mt-4 h-3 rounded-full bg-[#f7f2ff]">
              <div
                class="h-3 rounded-full bg-gradient-to-r from-[#c4b5fd] to-[#7c5cff]"
                :style="{ width: `${(category.votes / maxCategoryVotes) * 100}%` }"
              />
            </div>
          </div>
        </div>
      </Card>
    </section>

    <Card class="p-7">
      <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p class="text-xs font-semibold uppercase tracking-[0.26em] text-violet-500">Aktivitäten</p>
          <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Was gerade passiert ist</h2>
        </div>
        <p class="text-sm text-slate-500">Audit-nahe Ereignisse, komprimiert für den schnellen Blick.</p>
      </div>

      <div class="mt-6 grid gap-4 md:grid-cols-3">
        <div
          v-for="activity in activities"
          :key="activity.label"
          class="rounded-[24px] border border-violet-100 bg-violet-50/60 px-5 py-5"
        >
          <p class="font-semibold text-slate-800">{{ activity.label }}</p>
          <p class="mt-2 text-sm text-slate-500">{{ activity.age }}</p>
        </div>
        <p v-if="activities.length === 0" class="rounded-[26px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
          Noch keine aktuellen Audit-Aktivitäten vorhanden.
        </p>
      </div>
    </Card>
  </div>
</template>
