<script setup lang="ts">
import { Layers3, PlusCircle, Search, Tags, Trash2, TriangleAlert } from '@lucide/vue'

import AdminCategoryGroupModal from '../../components/admin/AdminCategoryGroupModal.vue'
import AdminCategoryOverviewModal from '../../components/admin/AdminCategoryOverviewModal.vue'
import AdminCategoryTemplatesModal from '../../components/admin/AdminCategoryTemplatesModal.vue'
import AdminCategoryTreeWorkspace from '../../components/admin/AdminCategoryTreeWorkspace.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminSeasonToolbar from '../../components/admin/AdminSeasonToolbar.vue'
import { useAdminCategoryManager } from '../../components/admin/useAdminCategoryManager'
import { watchAdminToast } from '../../composables/useAdminToast'
import Button from '../../components/ui/Button.vue'
import Card from '../../components/ui/Card.vue'
import Modal from '../../components/ui/Modal.vue'

const {
  selectedSeasonId,
  query,
  statusFilter,
  selectedGroupName,
  saving,
  adminMessage,
  adminError,
  groupModalOpen,
  editingGroupName,
  groupDraft,
  overviewTarget,
  overviewTitle,
  overviewSubtitle,
  overviewCategories,
  overviewCandidates,
  overviewNominations,
  filteredGroups,
  categoryStats,
  statusFilters,
  activeSubcategoryTemplates,
  focusedSubcategoryTemplate,
  subcategoryConfigModalOpen,
  subcategoryModalOpen,
  subcategoryDraft,
  subcategoryDrafts,
  subcategoryModalTitle,
  canSaveSubcategory,
  canSaveSubcategoryConfig,
  canCreateGroup,
  canSaveGroup,
  groupModalTitle,
  groupToDelete,
  deleting,
  openCreateGroupModal,
  openEditGroupModal,
  closeGroupModal,
  openSubcategoryConfigModal,
  closeSubcategoryConfigModal,
  openCreateSubcategoryModal,
  openEditSubcategoryModal,
  closeSubcategoryModal,
  fillSubcategorySlug,
  saveSubcategoryDraft,
  removeDraftSubcategory,
  saveSubcategoryConfig,
  saveGroupModal,
  confirmDeleteGroup,
  openGroupOverview,
  openCategoryOverview,
  isFocusedSubcategory,
  formatViewerRange,
  recommendedNominatorTarget,
} = useAdminCategoryManager()

watchAdminToast(adminMessage, adminError)
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Kategorien"
      :icon="Tags"
      description="Hauptkategorien und globale Unterkategorien werden getrennt gepflegt. Die Tree-Ansicht zeigt, wie viele Kandidaten und Nominierungen darunter liegen."
    />

    <AdminSeasonToolbar />

    <Card class="p-5">
      <div class="grid gap-4 xl:grid-cols-[minmax(260px,0.9fr)_minmax(0,1.1fr)_auto] xl:items-start">
        <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="Hauptkategorie oder Unterkategorie suchen"
          />
        </label>

        <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 class="flex flex-wrap gap-2 xl:justify-end">
          <Button variant="ghost" class="gap-2" @click="openSubcategoryConfigModal">
            <Layers3 class="h-4 w-4" />
            Unterkategorien konfigurieren
          </Button>
          <Button class="gap-2" :disabled="!selectedSeasonId || !canCreateGroup" @click="openCreateGroupModal">
            <PlusCircle class="h-4 w-4" />
            Hauptkategorie anlegen
          </Button>
        </div>
      </div>

      <div class="mt-4 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
        <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
        v-if="focusedSubcategoryTemplate"
        class="mt-4 rounded-2xl border border-sky-200 bg-sky-50/80 px-4 py-3 text-sm text-sky-900"
      >
        Fokus auf Unterkategorie:
        <strong>{{ focusedSubcategoryTemplate.name }}</strong>
        <span class="text-sky-700">({{ formatViewerRange(focusedSubcategoryTemplate.viewerRangeMin, focusedSubcategoryTemplate.viewerRangeMax) }})</span>
      </div>

      <p v-if="activeSubcategoryTemplates.length === 0" class="mt-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
        Lege zuerst mindestens eine Unterkategorie an, bevor du Hauptkategorien erzeugst.
      </p>
    </Card>

    <AdminCategoryTreeWorkspace
      :groups="filteredGroups"
      :selected-group-name="selectedGroupName"
      :is-focused="isFocusedSubcategory"
      :recommended-nominator-target="recommendedNominatorTarget"
      @edit-group="(group) => { selectedGroupName = group.name; openEditGroupModal(group) }"
      @overview-group="openGroupOverview"
      @overview-category="openCategoryOverview"
    />

    <AdminCategoryGroupModal
      :open="groupModalOpen"
      :title="groupModalTitle"
      :form="groupDraft"
      :can-save="canSaveGroup"
      :can-create-group="canCreateGroup"
      :saving="saving === (editingGroupName ?? 'new')"
      :is-editing="editingGroupName !== null"
      @close="closeGroupModal"
      @save="saveGroupModal"
      @delete="groupToDelete = filteredGroups.find((group) => group.name === editingGroupName) ?? null; closeGroupModal()"
    />

    <AdminCategoryTemplatesModal
      :open="subcategoryConfigModalOpen"
      :subcategories="subcategoryDrafts"
      :can-save="canSaveSubcategoryConfig"
      :saving="saving === 'templates'"
      :editor-open="subcategoryModalOpen"
      :editor-title="subcategoryModalTitle"
      :form="subcategoryDraft"
      :can-save-subcategory="canSaveSubcategory"
      @close="closeSubcategoryConfigModal"
      @save="saveSubcategoryConfig"
      @add-subcategory="openCreateSubcategoryModal"
      @edit-subcategory="openEditSubcategoryModal"
      @remove-subcategory="removeDraftSubcategory"
      @close-editor="closeSubcategoryModal"
      @save-subcategory="saveSubcategoryDraft"
      @fill-slug="fillSubcategorySlug"
    />

    <AdminCategoryOverviewModal
      :open="!!overviewTarget"
      :title="overviewTitle"
      :subtitle="overviewSubtitle"
      :categories="overviewCategories"
      :candidates="overviewCandidates"
      :nominations="overviewNominations"
      :recommended-nominator-target="recommendedNominatorTarget"
      @close="overviewTarget = null"
    />

    <Modal :open="!!groupToDelete" title="Hauptkategorie loeschen?" @close="groupToDelete = 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">{{ groupToDelete?.name }}</strong>" und alle automatisch darunter erzeugten Unterkategorien
          werden aus diesem Award-Jahr entfernt. Das laesst sich nicht rueckgaengig machen.
        </p>
      </div>
      <template #footer>
        <Button variant="ghost" @click="groupToDelete = null">Abbrechen</Button>
        <Button class="gap-2 !bg-rose-600 hover:!bg-rose-500" :disabled="deleting" @click="confirmDeleteGroup">
          <Trash2 class="h-4 w-4" />
          {{ deleting ? 'Loescht ...' : 'Endgueltig loeschen' }}
        </Button>
      </template>
    </Modal>
  </div>
</template>
