<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ClipboardList } from '@lucide/vue'
import { useRoute } from 'vue-router'

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

const store = useAwardsStore()
const route = useRoute()
const blacklistModalOpen = ref(false)
const selectedCategoryGroup = ref<string | null>(null)

const seasonDetail = computed(() => store.adminSeasonDetail)
const categoryStats = computed(() =>
  seasonDetail.value.categories.map((category) => ({
    ...category,
    pending: seasonDetail.value.pendingNominations.filter((nomination) => nomination.categoryId === category.id).length,
    candidates: seasonDetail.value.candidates.filter((candidate) => candidate.categoryId === category.id).length,
  })),
)
const mainCategoryStats = computed(() =>
  [...new Set(categoryStats.value.map((category) => category.groupName))]
    .map((groupName) => {
      const subcategories = categoryStats.value.filter((category) => category.groupName === groupName)
      return {
        groupName,
        pending: seasonDetail.value.pendingNominations.filter((nomination) => nomination.categoryGroupName === groupName).length,
        candidates: subcategories.reduce((sum, category) => sum + category.candidates, 0),
        subcategoryCount: subcategories.length,
        categoryIds: subcategories.map((category) => category.id),
        sortOrder: Math.min(...subcategories.map((category) => category.sortOrder)),
      }
    })
    .sort((a, b) => a.sortOrder - b.sortOrder || a.groupName.localeCompare(b.groupName)),
)
const selectedCategoryFilterIds = computed(() =>
  selectedCategoryGroup.value === null
    ? null
    : mainCategoryStats.value.find((category) => category.groupName === selectedCategoryGroup.value)?.categoryIds ?? null,
)
const reviewOverviewStats = computed(() => [
  { label: 'Hauptkategorien', value: new Set(seasonDetail.value.categories.map((category) => category.groupName)).size },
  { label: 'Unterkategorien', value: seasonDetail.value.categories.length },
  { label: 'Nominierungen', value: seasonDetail.value.pendingNominations.length + seasonDetail.value.reviewedNominations.length },
  { label: 'Noch zu bearbeiten', value: seasonDetail.value.pendingNominationGroups.length },
])

function applyRouteFilters() {
  const rawCategoryGroup = Array.isArray(route.query.categoryGroup) ? route.query.categoryGroup[0] : route.query.categoryGroup
  const rawCategoryId = Array.isArray(route.query.categoryId) ? route.query.categoryId[0] : route.query.categoryId
  const fallbackGroupName = mainCategoryStats.value[0]?.groupName ?? null

  if (typeof rawCategoryGroup === 'string' && rawCategoryGroup.trim()) {
    selectedCategoryGroup.value = mainCategoryStats.value.some((category) => category.groupName === rawCategoryGroup)
      ? rawCategoryGroup
      : fallbackGroupName
    return
  }

  const parsedCategoryId = Number(rawCategoryId)
  if (!Number.isFinite(parsedCategoryId) || parsedCategoryId <= 0) {
    selectedCategoryGroup.value = fallbackGroupName
    return
  }

  selectedCategoryGroup.value = seasonDetail.value.categories.find((category) => category.id === parsedCategoryId)?.groupName
    ?? fallbackGroupName
    ?? null
}

watch(
  () => [route.query.categoryId, route.query.categoryGroup, seasonDetail.value.categories.length] as const,
  () => {
    applyRouteFilters()
  },
  { immediate: true },
)
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Nominierungen"
      description="Nominierungen sichten, Kategorien priorisieren und Review-Fälle fokussiert entscheiden."
      :icon="ClipboardList"
    />

    <AdminSeasonToolbar />

    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
      <Card
        v-for="item in reviewOverviewStats"
        :key="item.label"
        class="rounded-[22px] px-5 py-5 shadow-[0_10px_28px_rgba(168,145,214,0.08)]"
      >
        <p class="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{{ item.label }}</p>
        <p class="mt-3 text-4xl font-bold text-slate-900">{{ item.value }}</p>
      </Card>
    </div>

    <Card class="overflow-hidden">
      <div class="grid gap-0 xl:grid-cols-[320px_minmax(0,1fr)]">
        <aside class="border-b border-violet-100 bg-[linear-gradient(180deg,#fcfaff_0%,#f8f4ff_100%)] xl:border-b-0 xl:border-r">
          <div class="border-b border-violet-100 px-5 py-5">
            <div>
              <p class="text-[11px] font-bold uppercase tracking-[0.22em] text-violet-500">Kategorien</p>
              <h2 class="mt-1 text-2xl font-bold text-slate-900">Hauptkategorien</h2>
            </div>
          </div>

          <div class="space-y-3 p-4">
            <button
              v-for="category in mainCategoryStats"
              :key="category.groupName"
              type="button"
              class="group w-full rounded-[24px] border px-4 py-4 text-left transition"
              :class="selectedCategoryGroup === category.groupName ? 'border-violet-300 bg-white shadow-[0_18px_38px_rgba(168,145,214,0.18)] ring-2 ring-violet-100' : 'border-violet-100 bg-white/80 hover:border-violet-200 hover:bg-white'"
              @click="selectedCategoryGroup = category.groupName"
            >
              <div class="flex items-start justify-between gap-3">
                <div class="min-w-0">
                  <div class="flex items-center gap-2">
                    <span
                      v-if="selectedCategoryGroup === category.groupName"
                      class="inline-flex h-2.5 w-2.5 rounded-full bg-violet-500 shadow-[0_0_0_6px_rgba(139,108,219,0.12)]"
                    />
                    <div class="truncate text-lg font-semibold text-slate-900">{{ category.groupName }}</div>
                  </div>
                  <div class="mt-1 text-sm" :class="selectedCategoryGroup === category.groupName ? 'text-violet-700' : 'text-slate-500'">{{ category.subcategoryCount }} Tiers · {{ category.candidates }} Kandidaten</div>
                </div>
                <span
                  class="inline-flex min-h-11 min-w-11 items-center justify-center rounded-full border px-3 text-base font-bold"
                  :class="selectedCategoryGroup === category.groupName ? 'border-violet-300 bg-violet-600 text-white' : 'border-violet-100 bg-violet-50 text-violet-700'"
                >
                  {{ category.pending }}
                </span>
              </div>
            </button>
          </div>
        </aside>

        <AdminReviewWorkspace
          :category-ids-filter="selectedCategoryFilterIds"
          :active-main-category="selectedCategoryGroup"
          :show-category-filter-chips="false"
          show-blacklist-button
          history-collapsible
          @open-blacklist="blacklistModalOpen = true"
        />
      </div>
    </Card>

    <AdminNominationLinkBlacklistModal :open="blacklistModalOpen" @close="blacklistModalOpen = false" />
  </div>
</template>
