<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { CalendarCog, Layers3, PlusCircle, Search } from '@lucide/vue'

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

const store = useAwardsStore()
const seasonSaving = ref(false)
const categorySaving = ref<number | 'new' | null>(null)
const adminMessage = ref('')
const adminError = ref('')

const seasonForm = reactive({
  currentPhase: '',
  isCurrent: false,
})

const newCategoryForm = reactive({
  groupName: '',
  name: '',
  slug: '',
  description: '',
  sortOrder: 1,
  maxNomineesPerUser: 3,
})

const editForms = reactive<Record<number, {
  groupName: string
  name: string
  slug: string
  description: string
  sortOrder: number
  maxNomineesPerUser: number
}>>({})

const seasonDetail = computed(() => store.adminSeasonDetail)
const selectedSeasonId = computed(() => store.adminSelectedSeasonId)
const categoryFilter = ref('')
const selectedCategoryId = ref<number | null>(null)
const categoryStats = computed(() => [
  { label: 'Kategorien', value: seasonDetail.value.categories.length },
  { label: 'Kandidaten', value: seasonDetail.value.candidates.length },
  { label: 'Reviews offen', value: seasonDetail.value.pendingNominations.length },
])
const filteredCategories = computed(() => {
  const query = categoryFilter.value.trim().toLowerCase()
  if (!query) return seasonDetail.value.categories
  return seasonDetail.value.categories.filter((category) =>
    [category.groupName, category.name, category.slug, category.description]
      .join(' ')
      .toLowerCase()
      .includes(query),
  )
})
const selectedCategory = computed(() =>
  filteredCategories.value.find((category) => category.id === selectedCategoryId.value) ?? filteredCategories.value[0] ?? null,
)

watch(
  seasonDetail,
  (detail) => {
    seasonForm.currentPhase = detail.currentPhase
    seasonForm.isCurrent = detail.isCurrent

    for (const category of detail.categories) {
      editForms[category.id] = {
        groupName: category.groupName,
        name: category.name,
        slug: category.slug,
        description: category.description,
        sortOrder: category.sortOrder,
        maxNomineesPerUser: category.maxNomineesPerUser,
      }
    }

    newCategoryForm.sortOrder = detail.categories.length + 1

    if (!detail.categories.some((category) => category.id === selectedCategoryId.value)) {
      selectedCategoryId.value = detail.categories[0]?.id ?? null
    }
  },
  { immediate: true },
)

watch(
  filteredCategories,
  (categories) => {
    if (!categories.some((category) => category.id === selectedCategoryId.value)) {
      selectedCategoryId.value = categories[0]?.id ?? null
    }
  },
  { immediate: true },
)

async function saveSeason() {
  if (!selectedSeasonId.value) return

  seasonSaving.value = true
  adminMessage.value = ''
  adminError.value = ''

  try {
    await store.updateAdminSeason(selectedSeasonId.value, {
      currentPhase: seasonForm.currentPhase,
      isCurrent: seasonForm.isCurrent,
    })
    adminMessage.value = 'Jahres-Einstellungen gespeichert.'
  } catch (error) {
    adminError.value = error instanceof Error ? error.message : 'Jahr konnte nicht gespeichert werden.'
  } finally {
    seasonSaving.value = false
  }
}

async function saveCategory(categoryId: number) {
  if (!selectedSeasonId.value) return

  categorySaving.value = categoryId
  adminMessage.value = ''
  adminError.value = ''

  try {
    await store.updateAdminCategory(categoryId, selectedSeasonId.value, editForms[categoryId])
    adminMessage.value = 'Kategorie gespeichert.'
  } catch (error) {
    adminError.value = error instanceof Error ? error.message : 'Kategorie konnte nicht gespeichert werden.'
  } finally {
    categorySaving.value = null
  }
}

async function createCategory() {
  if (!selectedSeasonId.value) return

  categorySaving.value = 'new'
  adminMessage.value = ''
  adminError.value = ''

  try {
    await store.createAdminCategory(selectedSeasonId.value, newCategoryForm)
    adminMessage.value = 'Neue Kategorie angelegt.'
    newCategoryForm.groupName = ''
    newCategoryForm.name = ''
    newCategoryForm.slug = ''
    newCategoryForm.description = ''
    newCategoryForm.sortOrder = seasonDetail.value.categories.length + 1
    newCategoryForm.maxNomineesPerUser = 3
  } catch (error) {
    adminError.value = error instanceof Error ? error.message : 'Kategorie konnte nicht angelegt werden.'
  } finally {
    categorySaving.value = null
  }
}
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Jahre"
      title="Jahr und Kategorien verwalten"
      description="Hier steuerst du die aktive Phase, legst neue Kategorien an und pflegst bestehende Gruppen, Limits und Beschreibungen."
      :icon="CalendarCog"
    />

    <AdminSeasonToolbar />

    <div class="grid gap-6 xl:grid-cols-[0.95fr_1.05fr]">
      <Card class="overflow-hidden">
        <div class="border-b border-violet-100 bg-gradient-to-br from-white via-violet-50/70 to-[#f7eef8] p-6">
          <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Jahresstatus</p>
              <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Award-Jahr steuern</h2>
              <p class="mt-2 max-w-xl text-sm leading-6 text-slate-500">
                Hier legst du fest, in welcher Phase das Jahr ist und ob genau dieses Jahr öffentlich für Community, Voting und Archiv sichtbar ist.
              </p>
            </div>
            <div class="rounded-2xl border px-4 py-3 text-sm font-semibold" :class="seasonForm.isCurrent ? 'border-emerald-100 bg-emerald-50 text-emerald-700' : 'border-slate-100 bg-slate-50 text-slate-500'">
              {{ seasonForm.isCurrent ? 'Öffentlich aktiv' : 'Intern vorbereitet' }}
            </div>
          </div>
        </div>

        <div class="space-y-5 p-6">
          <label class="block space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Aktuelle Phase</span>
            <input
              v-model="seasonForm.currentPhase"
              type="text"
              class="h-12 w-full rounded-2xl border border-violet-200 bg-white px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
              placeholder="z.B. Community Voting, Nominierung, Archiviert"
            />
            <span class="block text-xs leading-5 text-slate-500">
              Diese Phase wird als Orientierung für Team und später auch für Public-Kommunikation genutzt.
            </span>
          </label>

          <label class="flex cursor-pointer gap-4 rounded-[24px] border border-violet-100 bg-violet-50/50 p-4 transition hover:bg-violet-50">
            <input v-model="seasonForm.isCurrent" type="checkbox" class="mt-1 h-4 w-4 shrink-0 accent-violet-600" />
            <span>
              <span class="block font-semibold text-slate-800">Dieses Award-Jahr öffentlich schalten</span>
              <span class="mt-1 block text-sm leading-6 text-slate-500">
                Wenn aktiv, gilt dieses Jahr als aktueller Public-Kontext. Nur ein Award-Jahr sollte gleichzeitig öffentlich sein.
              </span>
            </span>
          </label>

          <div class="grid gap-3 sm:grid-cols-3">
            <div class="rounded-2xl border border-violet-50 bg-white/80 p-4">
              <p class="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Jahr</p>
              <strong class="mt-2 block text-xl text-violet-800">{{ seasonDetail.year || '-' }}</strong>
            </div>
            <div class="rounded-2xl border border-violet-50 bg-white/80 p-4">
              <p class="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Kategorien</p>
              <strong class="mt-2 block text-xl text-violet-800">{{ seasonDetail.categories.length }}</strong>
            </div>
            <div class="rounded-2xl border border-violet-50 bg-white/80 p-4">
              <p class="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Kandidaten</p>
              <strong class="mt-2 block text-xl text-violet-800">{{ seasonDetail.candidates.length }}</strong>
            </div>
          </div>

          <div class="flex flex-col gap-3 border-t border-violet-100 pt-5 sm:flex-row sm:items-center sm:justify-between">
            <p class="text-sm leading-6 text-slate-500">
              Speichert Phase und Public-Status für <strong class="text-slate-700">{{ seasonDetail.name }}</strong>.
            </p>
            <Button :disabled="seasonSaving || !selectedSeasonId" @click="saveSeason">
              {{ seasonSaving ? 'Speichert ...' : 'Jahresstatus speichern' }}
            </Button>
          </div>

          <p v-if="adminMessage" class="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="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{{ adminError }}</p>
        </div>
      </Card>

      <Card class="overflow-hidden">
        <div class="border-b border-violet-100 bg-gradient-to-br from-white via-[#f7f2ff] to-[#f7eef8] p-6">
          <div class="flex items-start gap-4">
            <div class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700">
              <PlusCircle class="h-5 w-5" />
            </div>
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Neue Kategorie</p>
              <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Kategorie planen</h2>
              <p class="mt-2 text-sm leading-6 text-slate-500">
                Lege zuerst Gruppe, Namen und Limit fest. Slug und Sortierung bestimmen später URL, Anzeige und Reihenfolge im Voting.
              </p>
            </div>
          </div>
        </div>

        <div class="space-y-4 p-6">
          <div class="grid gap-4 sm:grid-cols-2">
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Gruppe</span>
              <input v-model="newCategoryForm.groupName" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="z.B. Hauptpreise" />
            </label>
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Kategorie</span>
              <input v-model="newCategoryForm.name" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="z.B. VTuber des Jahres" />
            </label>
          </div>

          <label class="space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Beschreibung</span>
            <textarea v-model="newCategoryForm.description" class="min-h-28 w-full rounded-2xl border border-violet-200 px-4 py-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Kurz erklären, wofür diese Kategorie steht." />
          </label>

          <div class="grid gap-4 sm:grid-cols-3">
            <label class="space-y-2 sm:col-span-1">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Slug</span>
              <input v-model="newCategoryForm.slug" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="vtuber-des-jahres" />
            </label>
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Reihenfolge</span>
              <input v-model="newCategoryForm.sortOrder" type="number" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="1" />
            </label>
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Nominierungslimit</span>
              <input v-model="newCategoryForm.maxNomineesPerUser" type="number" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="3" />
            </label>
          </div>

          <div class="flex flex-col gap-3 border-t border-violet-100 pt-5 sm:flex-row sm:items-center sm:justify-between">
            <p class="text-sm leading-6 text-slate-500">
              Neue Kategorien sind sofort Teil des gewählten Award-Jahres und können danach unten weiter bearbeitet werden.
            </p>
            <Button :disabled="categorySaving === 'new' || !selectedSeasonId" @click="createCategory">
              {{ categorySaving === 'new' ? 'Erstellt ...' : 'Kategorie anlegen' }}
            </Button>
          </div>
        </div>
      </Card>
    </div>

    <Card class="overflow-hidden">
      <div class="border-b border-violet-100 bg-white/75 p-6">
        <div class="flex flex-col gap-5 xl:flex-row xl:items-end xl:justify-between">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Kategorien</p>
            <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">Kategorien dieses Jahres</h2>
            <p class="mt-2 max-w-2xl text-sm leading-6 text-slate-500">
              Prüfe Struktur, Slug, Limit und Kandidatenzahl pro Kategorie. Erst filtern, dann gezielt bearbeiten.
            </p>
          </div>
          <div class="grid gap-2 sm:grid-cols-3 xl:min-w-[380px]">
            <div v-for="stat in categoryStats" :key="stat.label" class="rounded-2xl border border-violet-50 bg-violet-50/50 px-3 py-2">
              <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">{{ stat.label }}</p>
              <strong class="mt-1 block text-lg text-violet-800">{{ stat.value }}</strong>
            </div>
          </div>
        </div>

        <div class="mt-5 grid gap-3 md:grid-cols-[minmax(0,1fr)_220px]">
          <label class="relative block">
            <Search class="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-violet-400" />
            <input
              v-model="categoryFilter"
              type="text"
              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="Nach Name, Gruppe oder Slug suchen"
            />
          </label>
          <div class="rounded-2xl border border-violet-100 bg-violet-50/60 px-4 py-3 text-sm text-slate-600">
            {{ filteredCategories.length }} / {{ seasonDetail.categories.length }} sichtbar
          </div>
        </div>
      </div>

      <div class="grid gap-5 p-6 xl:grid-cols-[minmax(320px,0.85fr)_minmax(0,1.15fr)]">
        <div class="space-y-2 xl:max-h-[680px] xl:overflow-y-auto xl:pr-2">
          <button
            v-for="category in filteredCategories"
            :key="category.id"
            type="button"
            class="w-full rounded-2xl border p-3 text-left transition"
            :class="selectedCategory?.id === category.id ? 'border-violet-200 bg-violet-50/80 shadow-[0_12px_30px_rgba(168,145,214,0.12)]' : 'border-violet-100 bg-white/85 hover:border-violet-200 hover:bg-violet-50/50'"
            @click="selectedCategoryId = category.id"
          >
            <div class="flex items-start justify-between gap-3">
              <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-2">
                  <span class="inline-flex items-center gap-1.5 rounded-full bg-white px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-violet-700">
                    <Layers3 class="h-3 w-3" />
                    {{ category.groupName }}
                  </span>
                  <span class="rounded-full bg-emerald-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-emerald-700">
                    {{ category.candidateCount }} Kandidaten
                  </span>
                  <span class="rounded-full bg-slate-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-600">
                    Limit {{ category.maxNomineesPerUser }}
                  </span>
                </div>
                <h3 class="mt-2 truncate text-base font-semibold text-slate-900">{{ category.name }}</h3>
                <p class="mt-1 line-clamp-2 text-sm leading-5 text-slate-500">{{ category.description }}</p>
              </div>
              <span class="shrink-0 rounded-xl border border-violet-100 bg-white px-2.5 py-1 text-xs font-semibold text-violet-800">
                #{{ category.sortOrder }}
              </span>
            </div>
          </button>

          <p v-if="filteredCategories.length === 0" class="rounded-[22px] border border-dashed border-violet-100 px-5 py-6 text-sm text-slate-500">
            Keine Kategorien passen zum aktuellen Filter.
          </p>
        </div>

        <div v-if="selectedCategory" class="rounded-[26px] border border-violet-100 bg-white/90 p-5 shadow-[0_14px_36px_rgba(168,145,214,0.08)]">
          <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div class="min-w-0">
              <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Kategorie bearbeiten</p>
              <h3 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">{{ selectedCategory.name }}</h3>
              <p class="mt-2 text-sm leading-6 text-slate-500">{{ selectedCategory.description }}</p>
            </div>
            <div class="flex flex-wrap gap-2">
              <span class="rounded-full border border-emerald-100 bg-emerald-50 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-700">
                {{ selectedCategory.candidateCount }} Kandidaten
              </span>
              <span class="rounded-full border border-slate-100 bg-slate-50 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-600">
                Limit {{ selectedCategory.maxNomineesPerUser }}
              </span>
            </div>
          </div>

          <div class="mt-5 grid gap-4 md:grid-cols-2">
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Gruppe</span>
              <input v-model="editForms[selectedCategory.id].groupName" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Gruppe" />
            </label>
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Name</span>
              <input v-model="editForms[selectedCategory.id].name" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Name" />
            </label>
            <label class="space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Slug</span>
              <input v-model="editForms[selectedCategory.id].slug" type="text" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="slug" />
            </label>
            <div class="grid gap-4 sm:grid-cols-2">
              <label class="space-y-2">
                <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Reihenfolge</span>
                <input v-model="editForms[selectedCategory.id].sortOrder" type="number" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="1" />
              </label>
              <label class="space-y-2">
                <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Limit</span>
                <input v-model="editForms[selectedCategory.id].maxNomineesPerUser" type="number" class="h-12 w-full rounded-2xl border border-violet-200 px-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="3" />
              </label>
            </div>
          </div>

          <label class="mt-4 block space-y-2">
            <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Beschreibung</span>
            <textarea
              v-model="editForms[selectedCategory.id].description"
              class="min-h-24 w-full rounded-2xl border border-violet-200 px-4 py-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100"
              placeholder="Beschreibung"
            />
          </label>

          <div class="mt-4 flex justify-end">
            <Button :disabled="categorySaving === selectedCategory.id" @click="saveCategory(selectedCategory.id)">
              {{ categorySaving === selectedCategory.id ? 'Speichert ...' : 'Kategorie speichern' }}
            </Button>
          </div>
        </div>
      </div>
    </Card>
  </div>
</template>
