<script setup lang="ts">
import { computed } from 'vue'
import { BarChart3, Clock3, Sparkles, Tags, Users, Vote } from '@lucide/vue'

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

const store = useAwardsStore()
const seasonDetail = computed(() => store.adminSeasonDetail)
const totalVotes = computed(() => store.admin.metrics.find((metric) => metric.label === 'Stimmen')?.value ?? 0)
const totalNominations = computed(() => store.admin.metrics.find((metric) => metric.label === 'Nominierungen')?.value ?? 0)
const maxVotes = computed(() => Math.max(...store.admin.topCategories.map((category) => category.votes), 1))
const categoryHealth = computed(() =>
  seasonDetail.value.categories
    .map((category) => ({
      name: category.name,
      groupName: category.groupName,
      candidates: seasonDetail.value.candidates.filter((candidate) => candidate.categoryId === category.id).length,
      reviews: seasonDetail.value.pendingNominations.filter((nomination) => nomination.categoryId === category.id).length,
    }))
    .sort((a, b) => b.candidates - a.candidates || b.reviews - a.reviews),
)
const metricCards = computed(() => [
  { label: 'Nominierungen', value: totalNominations.value, note: 'gesamt im Jahr', icon: Sparkles },
  { label: 'Stimmen', value: totalVotes.value, note: 'alle Votes', icon: Vote },
  { label: 'Kandidaten', value: seasonDetail.value.candidates.length, note: 'in allen Kategorien', icon: Users },
  { label: 'Reviews offen', value: seasonDetail.value.pendingNominations.length, note: 'Backlog', icon: Clock3 },
])
const insights = computed(() => {
  const categoriesWithoutCandidates = categoryHealth.value.filter((category) => category.candidates === 0).length
  const busiestReviewCategory = [...categoryHealth.value].sort((a, b) => b.reviews - a.reviews)[0]
  const votesPerCandidate = seasonDetail.value.candidates.length === 0 ? 0 : Math.round(totalVotes.value / seasonDetail.value.candidates.length)

  return [
    {
      label: 'Votes pro Kandidat',
      value: votesPerCandidate,
      note: 'Hilft einzuschätzen, ob die Kandidatenbasis breit genug ist.',
    },
    {
      label: 'Leere Kategorien',
      value: categoriesWithoutCandidates,
      note: categoriesWithoutCandidates === 0 ? 'Alle Kategorien sind besetzt.' : 'Diese Kategorien brauchen Kandidatenpflege.',
    },
    {
      label: 'Review-Hotspot',
      value: busiestReviewCategory?.reviews ?? 0,
      note: busiestReviewCategory ? busiestReviewCategory.name : 'Keine Review-Daten vorhanden.',
    },
  ]
})
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Analytics"
      title="Zahlen, die Entscheidungen helfen"
      description="Verdichte Voting-, Kategorie- und Review-Daten in eine Admin-Ansicht, damit das Team sofort erkennt, wo Reichweite, Lücken oder Backlog entstehen."
      :icon="BarChart3"
    />

    <AdminSeasonToolbar />

    <section class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      <Card v-for="metric in metricCards" :key="metric.label" class="p-5">
        <div class="flex items-start justify-between gap-4">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.18em] text-violet-500">{{ metric.label }}</p>
            <strong class="mt-3 block text-3xl text-violet-900">{{ metric.value.toLocaleString('de-DE') }}</strong>
            <p class="mt-2 text-sm text-slate-500">{{ metric.note }}</p>
          </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>
      </Card>
    </section>

    <section class="grid gap-6 xl:grid-cols-[1.08fr_0.92fr]">
      <Card class="p-6">
        <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Vote Performance</p>
        <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Top-Kategorien</h2>
        <div class="mt-6 space-y-4">
          <div v-for="category in store.admin.topCategories" :key="category.category" class="rounded-[22px] border border-violet-100 bg-white/90 p-4">
            <div class="flex items-center justify-between gap-4">
              <p class="font-semibold text-slate-900">{{ category.category }}</p>
              <strong class="text-violet-800">{{ category.votes.toLocaleString('de-DE') }}</strong>
            </div>
            <div class="mt-3 h-3 overflow-hidden rounded-full bg-[#f3ecff]">
              <div class="h-full rounded-full bg-[linear-gradient(90deg,#a78bfa,#f5a9d6,#f8d7a4)]" :style="{ width: `${(category.votes / maxVotes) * 100}%` }" />
            </div>
          </div>
        </div>
      </Card>

      <Card class="overflow-hidden">
        <div class="border-b border-violet-100 p-5">
          <div class="flex items-center justify-between gap-3">
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Kategorie Health</p>
              <h2 class="font-[Cormorant_Garamond] text-4xl text-violet-800">Abdeckung</h2>
            </div>
            <Tags class="h-6 w-6 text-violet-500" />
          </div>
        </div>
        <div class="max-h-[620px] divide-y divide-violet-50 overflow-y-auto">
          <div v-for="category in categoryHealth" :key="category.name" class="grid grid-cols-[minmax(0,1fr)_auto] gap-4 px-5 py-4">
            <div class="min-w-0">
              <p class="truncate font-semibold text-slate-900">{{ category.name }}</p>
              <p class="mt-1 truncate text-sm text-slate-500">{{ category.groupName }} · {{ category.reviews }} offene Reviews</p>
            </div>
            <span class="rounded-full border border-violet-100 bg-violet-50 px-3 py-1 text-sm font-semibold text-violet-700">
              {{ category.candidates }} Kandidaten
            </span>
          </div>
        </div>
      </Card>
    </section>

    <section class="grid gap-4 lg:grid-cols-3">
      <Card v-for="insight in insights" :key="insight.label" class="p-5">
        <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">{{ insight.label }}</p>
        <strong class="mt-3 block text-3xl text-violet-900">{{ insight.value.toLocaleString('de-DE') }}</strong>
        <p class="mt-2 text-sm leading-6 text-slate-500">{{ insight.note }}</p>
      </Card>
    </section>
  </div>
</template>
