<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { Layers3, PlusCircle, Search, Tags, Trash2, TriangleAlert } 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 Modal from '../../components/ui/Modal.vue'
import { useAwardsStore } from '../../stores/awards'
import type { AdminCategoryItem } from '../../types/awards'

const store = useAwardsStore()
const selectedSeasonId = computed(() => store.adminSelectedSeasonId)
const seasonDetail = computed(() => store.adminSeasonDetail)
const query = ref('')
const statusFilter = ref<'all' | 'empty' | 'reviews' | 'thin'>('all')
const selectedCategoryId = ref<number | null>(null)
const saving = ref<number | 'new' | null>(null)
const adminMessage = ref('')
const adminError = ref('')

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

const categoriesWithState = 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,
    }))
    .sort((a, b) => a.sortOrder - b.sortOrder),
)
const filteredCategories = computed(() => {
  const search = query.value.trim().toLowerCase()
  return categoriesWithState.value.filter((category) => {
    const matchesStatus =
      statusFilter.value === 'all' ||
      (statusFilter.value === 'empty' && category.candidates === 0) ||
      (statusFilter.value === 'reviews' && category.pending > 0) ||
      (statusFilter.value === 'thin' && category.candidates > 0 && category.candidates < Math.max(2, category.maxNomineesPerUser))
    const matchesSearch = !search || [category.groupName, category.name, category.slug, category.description]
      .join(' ')
      .toLowerCase()
      .includes(search)
    return matchesStatus && matchesSearch
  })
})
const selectedCategory = computed(() =>
  filteredCategories.value.find((category) => category.id === selectedCategoryId.value) ?? filteredCategories.value[0] ?? null,
)
const categoryStats = computed(() => [
  { label: 'Kategorien', value: seasonDetail.value.categories.length },
  { label: 'Kandidaten', value: seasonDetail.value.candidates.length },
  { label: 'Reviews', value: seasonDetail.value.pendingNominations.length },
])
const statusFilters = computed(() => [
  { key: 'all' as const, label: 'Alle', count: categoriesWithState.value.length },
  { key: 'empty' as const, label: 'Ohne Kandidaten', count: categoriesWithState.value.filter((category) => category.candidates === 0).length },
  { key: 'reviews' as const, label: 'Mit Reviews', count: categoriesWithState.value.filter((category) => category.pending > 0).length },
  { key: 'thin' as const, label: 'Dünn besetzt', count: categoriesWithState.value.filter((category) => category.candidates > 0 && category.candidates < Math.max(2, category.maxNomineesPerUser)).length },
])

watch(
  seasonDetail,
  (detail) => {
    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
  }
})

async function saveCategory(categoryId: number) {
  if (!selectedSeasonId.value) return
  saving.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 {
    saving.value = null
  }
}

async function createCategory() {
  if (!selectedSeasonId.value) return
  saving.value = 'new'
  adminMessage.value = ''
  adminError.value = ''
  try {
    await store.createAdminCategory(selectedSeasonId.value, newCategoryForm)
    adminMessage.value = '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 {
    saving.value = null
  }
}

function slugify(value: string) {
  return value
    .trim()
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

function fillNewSlug() {
  newCategoryForm.slug = slugify(newCategoryForm.name)
}

const categoryToDelete = ref<AdminCategoryItem | null>(null)
const deleting = ref(false)

async function confirmDeleteCategory() {
  if (!categoryToDelete.value || !selectedSeasonId.value) return
  deleting.value = true
  adminError.value = ''
  try {
    await store.deleteAdminCategory(categoryToDelete.value.id, selectedSeasonId.value)
    adminMessage.value = `Kategorie „${categoryToDelete.value.name}" wurde gelöscht.`
    categoryToDelete.value = null
  } catch (error) {
    adminError.value = error instanceof Error ? error.message : 'Löschen fehlgeschlagen.'
  } finally {
    deleting.value = false
  }
}
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Kategorien"
      title="Award-Struktur pflegen"
      description="Eine kompakte Arbeitsansicht für viele Kategorien: links filtern und auswählen, rechts gezielt Gruppe, Slug, Limit und Beschreibung bearbeiten."
      :icon="Tags"
    />

    <AdminSeasonToolbar />

    <section class="grid gap-6 xl:grid-cols-[minmax(320px,0.82fr)_minmax(0,1.18fr)]">
      <Card class="overflow-hidden">
        <div class="border-b border-violet-100 p-5">
          <div class="grid gap-3">
            <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="query" class="h-12 w-full rounded-2xl border border-violet-200 bg-white pl-11 pr-4 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Kategorie, Gruppe oder Slug suchen" />
            </label>
            <div class="grid grid-cols-3 gap-2">
              <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="truncate text-[10px] font-semibold uppercase tracking-[0.12em] text-slate-500">{{ stat.label }}</p>
                <strong class="text-lg text-violet-800">{{ stat.value }}</strong>
              </div>
            </div>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="filter in statusFilters"
                :key="filter.key"
                type="button"
                class="rounded-full border px-3 py-1.5 text-xs font-semibold transition"
                :class="statusFilter === filter.key ? 'border-violet-200 bg-violet-100 text-violet-800' : 'border-violet-100 bg-white text-slate-600 hover:bg-violet-50'"
                @click="statusFilter = filter.key"
              >
                {{ filter.label }} · {{ filter.count }}
              </button>
            </div>
          </div>
        </div>

        <div class="max-h-[700px] space-y-2 overflow-y-auto p-4">
          <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:bg-violet-50/50'"
            @click="selectedCategoryId = category.id"
          >
            <div class="flex items-start justify-between gap-3">
              <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.slug }}</p>
                <div class="mt-2 flex flex-wrap gap-1.5">
                  <span class="rounded-full bg-emerald-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-emerald-700">{{ category.candidates }} Kandidaten</span>
                  <span class="rounded-full bg-violet-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-violet-700">Limit {{ category.maxNomineesPerUser }}</span>
                  <span v-if="category.pending" class="rounded-full bg-amber-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-amber-700">{{ category.pending }} Reviews</span>
                  <span v-if="category.candidates === 0" class="rounded-full bg-rose-50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-rose-700">leer</span>
                </div>
              </div>
              <span class="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>
        </div>
      </Card>

      <div class="space-y-6">
        <Card v-if="selectedCategory" class="p-6">
          <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Kategorie bearbeiten</p>
              <h2 class="mt-2 font-[Cormorant_Garamond] text-4xl text-violet-800">{{ selectedCategory.name }}</h2>
              <p class="mt-2 text-sm leading-6 text-slate-500">{{ selectedCategory.description }}</p>
            </div>
            <div class="grid h-12 w-12 place-items-center rounded-2xl bg-violet-100 text-violet-700">
              <Layers3 class="h-5 w-5" />
            </div>
          </div>

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

          <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" 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" />
            </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" 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" />
            </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" 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" />
            </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" />
              </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" />
              </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" />
          </label>

          <div class="mt-5 flex items-center justify-between gap-3">
            <Button variant="ghost" class="gap-2 border border-rose-200 text-rose-600 hover:bg-rose-50" @click="categoryToDelete = selectedCategory">
              <Trash2 class="h-4 w-4" /> Löschen
            </Button>
            <Button :disabled="saving === selectedCategory.id" @click="saveCategory(selectedCategory.id)">
              {{ saving === selectedCategory.id ? 'Speichert …' : 'Kategorie speichern' }}
            </Button>
          </div>
        </Card>

        <Card class="p-6">
          <div class="flex items-start gap-4">
            <div class="grid h-11 w-11 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">Neu</p>
              <h2 class="mt-1 font-[Cormorant_Garamond] text-3xl text-violet-800">Kategorie anlegen</h2>
            </div>
          </div>

          <div class="mt-5 grid gap-4 md:grid-cols-2">
            <input v-model="newCategoryForm.groupName" class="h-12 rounded-2xl border border-violet-200 px-4 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Gruppe" />
            <input v-model="newCategoryForm.name" class="h-12 rounded-2xl border border-violet-200 px-4 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Kategorie" />
            <div class="flex gap-2">
              <input v-model="newCategoryForm.slug" class="h-12 min-w-0 flex-1 rounded-2xl border border-violet-200 px-4 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="slug" />
              <button type="button" class="h-12 rounded-2xl border border-violet-100 bg-violet-50 px-4 text-xs font-semibold text-violet-700 transition hover:bg-violet-100" @click="fillNewSlug">
                Auto
              </button>
            </div>
            <div class="grid gap-4 sm:grid-cols-2">
              <input v-model="newCategoryForm.sortOrder" type="number" class="h-12 rounded-2xl border border-violet-200 px-4 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Reihenfolge" />
              <input v-model="newCategoryForm.maxNomineesPerUser" type="number" class="h-12 rounded-2xl border border-violet-200 px-4 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Limit" />
            </div>
          </div>
          <textarea v-model="newCategoryForm.description" class="mt-4 min-h-20 w-full rounded-2xl border border-violet-200 px-4 py-3 text-sm outline-none focus:border-violet-400 focus:ring-4 focus:ring-violet-100" placeholder="Beschreibung" />
          <div class="mt-4 flex justify-end">
            <Button :disabled="saving === 'new' || !selectedSeasonId" @click="createCategory">
              {{ saving === 'new' ? 'Erstellt ...' : 'Kategorie anlegen' }}
            </Button>
          </div>
        </Card>
      </div>
    </section>

    <Modal :open="!!categoryToDelete" title="Kategorie löschen?" @close="categoryToDelete = null">
      <div class="flex items-start gap-4">
        <span class="grid h-12 w-12 shrink-0 place-items-center rounded-full bg-rose-50 text-rose-500">
          <TriangleAlert class="h-6 w-6" />
        </span>
        <p class="text-sm leading-7 text-slate-600">
          „<strong class="text-slate-800">{{ categoryToDelete?.name }}</strong>" und alle zugehörigen Kandidaten werden aus diesem
          Award-Jahr entfernt. Das lässt sich nicht rückgängig machen.
        </p>
      </div>
      <template #footer>
        <Button variant="ghost" @click="categoryToDelete = null">Abbrechen</Button>
        <Button class="!bg-rose-600 hover:!bg-rose-500" :disabled="deleting" @click="confirmDeleteCategory">
          {{ deleting ? 'Löscht …' : 'Endgültig löschen' }}
        </Button>
      </template>
    </Modal>
  </div>
</template>
