<script setup lang="ts">
import { AlertTriangle, Clock3, EyeOff, Filter, Trophy, UploadCloud } from '@lucide/vue'

import AdminWinnersTreeWorkspace from '../../components/admin/AdminWinnersTreeWorkspace.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminSeasonToolbar from '../../components/admin/AdminSeasonToolbar.vue'
import { useAdminWinnersManager } from '../../components/admin/useAdminWinnersManager'
import { watchAdminToast } from '../../composables/useAdminToast'
import Button from '../../components/ui/Button.vue'
import Card from '../../components/ui/Card.vue'

const {
  adminError,
  adminMessage,
  clearFilters,
  deletingResultId,
  focusedCategoryId,
  publicationState,
  publishingWinners,
  query,
  savingResultForCategory,
  selectedGroupName,
  selectGroup,
  focusCategory,
  statusFilter,
  statusFilters,
  summaryCards,
  winnerGroups,
  winnerSelections,
  unpublishingWinners,
  clearWinner,
  publishWinners,
  saveWinner,
  selectedWinnerIdentitySummary,
  unpublishWinners,
  winnerRuleNoticeFor,
} = useAdminWinnersManager()

watchAdminToast(adminMessage, adminError)
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Gewinner"
      description="Finale Gewinner pro Unterkategorie setzen, Guards prüfen und Landingpage-Freigabe vorbereiten."
      :icon="Trophy"
    />

    <AdminSeasonToolbar />

    <Card class="p-5">
      <div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_auto] xl:items-start">
        <div class="min-w-0">
          <div class="flex flex-wrap items-center gap-2">
            <span class="inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-bold uppercase tracking-[0.12em]" :class="publicationState.statusTone">
              <UploadCloud v-if="!publicationState.isPublished" class="h-4 w-4" />
              <Trophy v-else class="h-4 w-4" />
              {{ publicationState.statusLabel }}
            </span>
            <span class="rounded-full border border-violet-100 bg-violet-50 px-3 py-1.5 text-xs font-semibold text-violet-700">
              Phase: {{ publicationState.phaseLabel }}
            </span>
          </div>
          <h2 class="mt-3 text-xl font-bold text-slate-900">Landingpage-Freigabe</h2>
          <p class="mt-1 max-w-3xl text-sm leading-6 text-slate-500">
            Gewinner bleiben intern, bis dieses Award-Jahr veröffentlicht wird. Nach der Freigabe erscheinen sie auf der Landingpage; der bisherige Landingpage-Jahrgang wandert ins Archiv.
          </p>
          <p class="mt-3 text-sm font-semibold text-slate-600">
            {{ publicationState.publishedAtLabel }}
            <span v-if="publicationState.isPublished" class="text-slate-400">· {{ publicationState.publishedByLabel }}</span>
          </p>

          <div v-if="publicationState.issues.length > 0" class="mt-4 grid gap-2 sm:grid-cols-2">
            <div
              v-for="issue in publicationState.issues"
              :key="issue.key"
              class="rounded-2xl border px-4 py-3"
              :class="issue.isWarning ? 'border-amber-100 bg-amber-50 text-amber-800' : 'border-violet-100 bg-violet-50 text-violet-800'"
            >
              <div class="flex items-start gap-2">
                <AlertTriangle v-if="issue.isWarning" class="mt-0.5 h-4 w-4 shrink-0" />
                <Clock3 v-else class="mt-0.5 h-4 w-4 shrink-0" />
                <div>
                  <p class="text-sm font-bold">{{ issue.label }}</p>
                  <p class="mt-1 text-xs leading-5 opacity-80">{{ issue.note }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="flex flex-wrap gap-2 xl:justify-end">
          <Button
            :disabled="publicationState.isPublished || !publicationState.canPublish || publishingWinners"
            class="gap-2"
            @click="publishWinners"
          >
            <UploadCloud class="h-4 w-4" />
            {{ publishingWinners ? 'Veröffentlicht ...' : publicationState.isPublished ? 'Veröffentlicht' : 'Veröffentlichen' }}
          </Button>
          <Button
            v-if="publicationState.isPublished"
            variant="secondary"
            class="gap-2"
            :disabled="unpublishingWinners"
            @click="unpublishWinners"
          >
            <EyeOff class="h-4 w-4" />
            {{ unpublishingWinners ? 'Nimmt zurück ...' : 'Zurücknehmen' }}
          </Button>
        </div>
      </div>
    </Card>

    <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
      <Card v-for="card in summaryCards" :key="card.label" class="p-4">
        <div class="flex items-start justify-between gap-3">
          <div class="min-w-0">
            <p class="text-[11px] font-bold uppercase tracking-[0.16em] text-slate-500">{{ card.label }}</p>
            <strong class="mt-2 block text-2xl text-slate-950">{{ card.value }}</strong>
            <p class="mt-1 text-sm leading-5 text-slate-500">{{ card.note }}</p>
          </div>
          <div class="grid h-10 w-10 shrink-0 place-items-center rounded-xl border" :class="card.tone">
            <component :is="card.icon" class="h-5 w-5" />
          </div>
        </div>

        <div v-if="typeof card.progress === 'number'" class="mt-4">
          <div class="h-3 overflow-hidden rounded-full bg-violet-100">
            <div class="h-full rounded-full bg-[linear-gradient(90deg,#8b5cf6,#22c55e)] transition-all" :style="{ width: `${card.progress}%` }" />
          </div>
        </div>
      </Card>
    </section>

    <section class="grid gap-4 xl:grid-cols-[minmax(260px,0.9fr)_minmax(0,1.1fr)_auto] xl:items-center">
      <label class="relative block">
        <Filter class="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-violet-400" />
        <input
          v-model="query"
          type="search"
          class="h-12 w-full rounded-2xl border border-violet-200 bg-white/90 pl-11 pr-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
          placeholder="Hauptkategorie, Unterkategorie oder Gewinner suchen"
        >
      </label>

      <div class="flex flex-wrap gap-2">
        <button
          v-for="option in statusFilters"
          :key="option.value"
          type="button"
          class="inline-flex items-center gap-2 rounded-full border bg-white/90 px-3 py-1.5 text-xs font-semibold transition"
          :class="statusFilter === option.value ? 'border-violet-200 bg-violet-100 text-violet-800' : 'border-violet-100 text-slate-600 hover:bg-violet-50'"
          @click="statusFilter = option.value"
        >
          {{ option.label }}
          <span class="rounded-full bg-white/70 px-2 py-0.5 text-[11px]">{{ option.count }}</span>
        </button>
      </div>

      <div class="flex items-center justify-end">
        <Button
          v-if="query || statusFilter !== 'all'"
          variant="ghost"
          class="shrink-0"
          @click="clearFilters"
        >
          Filter reset
        </Button>
      </div>
    </section>

    <AdminWinnersTreeWorkspace
      :groups="winnerGroups"
      :selected-group-name="selectedGroupName"
      :focused-category-id="focusedCategoryId"
      :winner-selections="winnerSelections"
      :saving-result-for-category="savingResultForCategory"
      :deleting-result-id="deletingResultId"
      :selected-winner-identity-summary="selectedWinnerIdentitySummary"
      :winner-rule-notice-for="winnerRuleNoticeFor"
      @select-group="selectGroup"
      @select-category="focusCategory"
      @update:winner-selection="(categoryId: number, value: string) => { winnerSelections[categoryId] = value }"
      @save="saveWinner"
      @clear="clearWinner"
    />
  </div>
</template>
