<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  AlertTriangle,
  CalendarCog,
  CheckCircle2,
  ExternalLink,
  History,
  PlusCircle,
} from '@lucide/vue'
import { RouterLink } from 'vue-router'

import AdminSeasonCreateModal from '../../components/admin/AdminSeasonCreateModal.vue'
import AdminSeasonDeleteModal from '../../components/admin/AdminSeasonDeleteModal.vue'
import AdminSeasonOverviewCard from '../../components/admin/AdminSeasonOverviewCard.vue'
import AdminPageHeader from '../../components/admin/AdminPageHeader.vue'
import AdminSeasonWorkflowCard from '../../components/admin/AdminSeasonWorkflowCard.vue'
import { useAdminSeasonManager } from '../../components/admin/useAdminSeasonManager'
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 {
  store,
  form,
  createForm,
  saving,
  adminMessage,
  adminError,
  createModalOpen,
  creating,
  completing,
  seasonToDelete,
  deleting,
  seasonDetail,
  selectedSeasonId,
  readinessItems,
  archiveReadinessIssues,
  canActivatePublic,
  phasePresets,
  canDeleteSelectedSeason,
  canCompleteSelectedSeason,
  createPublicReadinessIssues,
  copySourceOptions,
  loadingSeasonAudit,
  latestSeasonAuditSummary,
  latestSeasonAuditMeta,
  canCreate,
  phaseGateway,
  activatePublicSeason,
  requestPhaseGateway,
  requestCompletionGateway,
  confirmPhaseGateway,
  openCreateModal,
  saveSeason,
  createSeason,
  openDeleteSeasonModal,
  confirmDeleteSeason,
} = useAdminSeasonManager()

watchAdminToast(adminMessage, adminError)

// ---------- Season switching ----------
const switchingSeasonId = ref<number | null>(null)
async function selectSeason(seasonId: number) {
  if (seasonId === selectedSeasonId.value || switchingSeasonId.value) return
  switchingSeasonId.value = seasonId
  try {
    await store.loadAdminSeasonDetail(seasonId)
  } finally {
    switchingSeasonId.value = null
  }
}

function requestCompleteSeason() {
  if (completing.value || !canCompleteSelectedSeason.value) return
  void requestCompletionGateway()
}

// ---------- Quick stats ----------
const quickStats = computed(() => {
  const d = seasonDetail.value
  const pendingClips = d.clipSubmissions.filter((c) => c.status === 'pending').length
  return [
    { label: 'Kategorien', value: d.categories.length },
    { label: 'Kandidaten', value: d.candidates.length },
    { label: 'Nominierungen', value: d.pendingNominations.length, warn: d.pendingNominations.length > 0 },
    { label: 'Clips offen', value: pendingClips, warn: pendingClips > 0 },
    { label: 'Gewinner', value: d.results.length },
  ]
})

// ---------- Readiness score ----------
const readinessScore = computed(() => {
  const done = readinessItems.value.filter((i) => i.complete).length
  return { done, total: readinessItems.value.length }
})
</script>

<template>
  <div class="space-y-6">
    <AdminPageHeader
      eyebrow="Jahre"
      description="Award-Jahr wählen, Phase steuern, Timeline pflegen."
      :icon="CalendarCog"
    />

    <!-- ═══ Jahr-Auswahl ═══ -->
    <Card class="overflow-hidden">
      <div class="flex items-center justify-between gap-3 border-b border-violet-100 px-5 py-3.5">
        <p class="text-xs font-semibold uppercase tracking-[0.22em] text-violet-500">Award-Jahre</p>
        <Button variant="ghost" size="sm" class="gap-1.5 border border-violet-100 text-violet-700 hover:bg-violet-50" @click="openCreateModal">
          <PlusCircle class="h-4 w-4" />
          Neu
        </Button>
      </div>
      <div class="flex gap-2 overflow-x-auto px-5 py-4">
        <button
          v-for="season in store.adminSeasons"
          :key="season.id"
          type="button"
          class="flex shrink-0 flex-col gap-1.5 rounded-[20px] border px-4 py-3 text-left transition"
          :class="season.id === selectedSeasonId
            ? 'border-violet-300 bg-[linear-gradient(135deg,#ece2ff,#fff2dd)] shadow-[0_12px_28px_rgba(139,108,219,0.18)]'
            : 'border-violet-100 bg-white/80 hover:border-violet-200 hover:bg-violet-50/60'"
          @click="selectSeason(season.id)"
        >
          <div class="flex items-center gap-2">
            <strong class="text-2xl leading-none" :class="season.id === selectedSeasonId ? 'text-violet-900' : 'text-slate-700'">
              {{ season.year }}
            </strong>
            <span
              class="rounded-full border px-2 py-0.5 text-[10px] font-bold"
              :class="season.isCurrent
                ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
                : 'border-slate-200 bg-slate-50 text-slate-500'"
            >
              {{ season.isCurrent ? 'Public' : 'Intern' }}
            </span>
          </div>
          <p class="max-w-[180px] truncate text-xs text-slate-500">{{ season.name }}</p>
          <span class="rounded-full border border-violet-100 bg-white/80 px-2.5 py-0.5 text-[11px] font-semibold text-violet-700">
            {{ season.currentPhase }}
          </span>
        </button>

        <button
          v-if="store.adminSeasons.length === 0"
          type="button"
          class="flex shrink-0 items-center gap-2 rounded-[20px] border border-dashed border-violet-200 px-6 py-4 text-sm font-semibold text-violet-500 hover:bg-violet-50"
          @click="openCreateModal"
        >
          <PlusCircle class="h-4 w-4" />
          Erstes Jahr anlegen
        </button>
      </div>
    </Card>

    <AdminSeasonOverviewCard
      v-if="selectedSeasonId"
      :form="form"
      :saving="saving"
      :completing="completing"
      :quick-stats="quickStats"
      :can-delete-selected-season="canDeleteSelectedSeason"
      :can-activate-public="canActivatePublic"
      :can-complete-selected-season="canCompleteSelectedSeason"
      :open-delete-season-modal="openDeleteSeasonModal"
      :activate-public-season="activatePublicSeason"
      :request-complete-season="requestCompleteSeason"
      :save-season="saveSeason"
    />

    <!-- ═══ Grunddaten + Readiness ═══ -->
    <section v-if="selectedSeasonId" class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_380px]">
      <!-- Grunddaten -->
      <Card class="p-6">
        <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Grunddaten</p>
        <h2 class="mt-1 text-lg font-bold text-slate-900">Stammdaten bearbeiten</h2>

        <div class="mt-5 space-y-4">
          <div class="grid gap-4 sm:grid-cols-[140px_minmax(0,1fr)]">
            <label class="block space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Jahr</span>
              <input
                v-model.number="form.year"
                type="number"
                placeholder="2027"
                :disabled="saving"
                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 disabled:bg-slate-50 disabled:text-slate-400"
              />
            </label>
            <label class="block space-y-2">
              <span class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Name</span>
              <input
                v-model="form.name"
                type="text"
                placeholder="VTuber Star Awards 2027"
                :disabled="saving"
                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 disabled:bg-slate-50 disabled:text-slate-400"
              />
            </label>
          </div>

          <div class="rounded-[22px] border border-violet-100 bg-violet-50/60 p-4">
            <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <div class="min-w-0">
                <p class="text-xs font-semibold uppercase tracking-[0.18em] text-violet-500">Finale-Banner</p>
                <h3 class="mt-1 text-base font-bold text-slate-900">Live-Button im Landingpage-Content pflegen</h3>
                <p class="mt-1 text-sm leading-6 text-slate-500">
                  Der Link für den Finale-Button wird zentral im Landingpage-Modul gepflegt.
                </p>
              </div>
              <RouterLink
                to="/admin/content?editor=streamBanner"
                class="inline-flex shrink-0 items-center justify-center gap-2 rounded-2xl border border-violet-200 bg-white px-4 py-3 text-sm font-semibold text-violet-700 transition hover:bg-violet-100"
              >
                Finale-Banner öffnen
                <ExternalLink class="h-4 w-4" />
              </RouterLink>
            </div>
          </div>

          <div class="grid gap-3 sm:grid-cols-2">
            <label class="flex cursor-pointer gap-3 rounded-[22px] border border-violet-100 bg-violet-50/50 p-4 transition hover:bg-violet-50 has-disabled:opacity-70">
              <input v-model="form.isCommunityOnly" type="checkbox" class="mt-1 h-4 w-4 shrink-0 accent-violet-600" :disabled="saving" />
              <span>
                <span class="block font-semibold text-slate-800">Community-only</span>
                <span class="mt-1 block text-sm leading-5 text-slate-500">Voting und Teilnahme über die Community.</span>
              </span>
            </label>
            <label
              class="flex cursor-pointer gap-3 rounded-[22px] border p-4 transition"
              :class="form.isCurrent
                ? 'border-emerald-200 bg-emerald-50/60 hover:bg-emerald-50'
                : 'border-violet-100 bg-violet-50/50 hover:bg-violet-50 has-disabled:opacity-70'"
            >
              <input
                v-model="form.isCurrent"
                type="checkbox"
                class="mt-1 h-4 w-4 shrink-0 accent-violet-600"
                :disabled="saving || (!form.isCurrent && !canActivatePublic)"
              />
              <span>
                <span class="block font-semibold text-slate-800">Public-Kontext</span>
                <span class="mt-1 block text-sm leading-5 text-slate-500">
                  {{ form.isCurrent ? 'Aktiv auf der Landingpage.' : canActivatePublic ? 'Kann aktiviert werden.' : 'Readiness-Blocker auflösen.' }}
                </span>
              </span>
            </label>
          </div>

          <!-- Audit entry -->
          <div class="flex items-start gap-3 rounded-[22px] border border-violet-100 bg-white p-4">
            <span class="grid h-10 w-10 shrink-0 place-items-center rounded-2xl bg-violet-100 text-violet-700">
              <History class="h-5 w-5" />
            </span>
            <div class="min-w-0">
              <p class="text-xs font-semibold uppercase tracking-[0.18em] text-violet-500">Letzte Admin-Aktion</p>
              <p class="mt-1 text-sm font-semibold leading-5 text-slate-800">
                {{ loadingSeasonAudit ? 'Lädt Audit …' : latestSeasonAuditSummary }}
              </p>
              <p class="mt-0.5 text-xs text-slate-500">{{ latestSeasonAuditMeta }}</p>
            </div>
          </div>
        </div>
      </Card>

      <!-- Readiness -->
      <Card class="p-6">
        <div class="flex items-center justify-between gap-3">
          <div>
            <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">Readiness</p>
            <h2 class="mt-1 text-lg font-bold text-slate-900">Checkliste</h2>
          </div>
          <div
            class="flex items-center gap-2 rounded-2xl border px-3 py-2 text-xs font-bold"
            :class="canActivatePublic ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-rose-200 bg-rose-50 text-rose-700'"
          >
            <span class="h-2 w-2 rounded-full" :class="canActivatePublic ? 'bg-emerald-500' : 'bg-rose-500'" />
            {{ readinessScore.done }}/{{ readinessScore.total }} bereit
          </div>
        </div>

        <!-- Readiness progress bar -->
        <div class="mt-4">
          <div class="h-2 overflow-hidden rounded-full bg-slate-100">
            <div
              class="h-full rounded-full transition-all duration-500"
              :class="canActivatePublic ? 'bg-emerald-500' : 'bg-violet-500'"
              :style="{ width: `${(readinessScore.done / readinessScore.total) * 100}%` }"
            />
          </div>
        </div>

        <div class="mt-4 grid gap-2">
          <RouterLink
            v-for="item in readinessItems"
            :key="item.label"
            :to="item.to"
            class="group flex items-start gap-3 rounded-2xl border px-4 py-3 transition hover:shadow-sm"
            :class="item.complete
              ? 'border-emerald-100 bg-emerald-50/60 hover:bg-emerald-50'
              : item.blocking
                ? 'border-rose-200 bg-rose-50/60 hover:bg-rose-50'
                : 'border-amber-100 bg-amber-50/60 hover:bg-amber-50'"
          >
            <CheckCircle2 v-if="item.complete" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-600" />
            <AlertTriangle v-else class="mt-0.5 h-4 w-4 shrink-0" :class="item.blocking ? 'text-rose-600' : 'text-amber-600'" />
            <span class="min-w-0 flex-1">
              <span class="flex flex-wrap items-center gap-2 text-sm font-semibold text-slate-800">
                {{ item.label }}
                <span v-if="item.blocking && !item.complete" class="rounded-full bg-rose-100 px-2 py-0.5 text-[10px] font-bold text-rose-700">Blocker</span>
              </span>
              <span class="mt-0.5 block text-xs leading-5 text-slate-500">{{ item.note }}</span>
            </span>
            <ExternalLink class="mt-1 h-3.5 w-3.5 shrink-0 text-slate-400 opacity-0 transition group-hover:opacity-100" />
          </RouterLink>
        </div>

        <div v-if="archiveReadinessIssues.length > 0" class="mt-4 rounded-[22px] border border-rose-200 bg-rose-50 px-4 py-3 text-sm leading-6 text-rose-700">
          <strong class="block text-rose-800">Abschluss blockiert.</strong>
          {{ archiveReadinessIssues.join(' ') }}
        </div>
      </Card>
    </section>

    <AdminSeasonWorkflowCard
      v-if="selectedSeasonId"
      :form="form"
      :saving="saving"
      :selected-season-id="selectedSeasonId"
      :save-season="saveSeason"
      :request-phase-gateway="requestPhaseGateway"
    />

    <!-- Empty state -->
    <Card v-else class="px-8 py-16 text-center">
      <CalendarCog class="mx-auto h-8 w-8 text-violet-300" />
      <p class="mt-4 text-sm text-slate-500">Noch keine Award-Jahre geladen.</p>
      <Button class="mx-auto mt-5 gap-2" @click="openCreateModal">
        <PlusCircle class="h-4 w-4" />
        Erstes Jahr anlegen
      </Button>
    </Card>
  </div>

  <!-- Modals (unverändert) -->
  <AdminSeasonCreateModal
    :open="createModalOpen"
    :create-form="createForm"
    :creating="creating"
    :can-create="canCreate"
    :copy-source-options="copySourceOptions"
    :create-public-readiness-issues="createPublicReadinessIssues"
    :phase-presets="phasePresets"
    :on-close="() => { createModalOpen = false }"
    :on-create="createSeason"
  />

  <AdminSeasonDeleteModal
    :season-to-delete="seasonToDelete"
    :deleting="deleting"
    :on-close="() => { seasonToDelete = null }"
    :on-confirm-delete="confirmDeleteSeason"
  />

  <Modal
    :open="!!phaseGateway"
    :title="phaseGateway?.title || 'Check-Gateway'"
    :subtitle="phaseGateway?.subtitle || ''"
    @close="phaseGateway = null"
  >
    <div v-if="phaseGateway" class="space-y-4">
      <div v-if="phaseGateway.blockers.length" class="rounded-[24px] border border-rose-200 bg-rose-50 p-4">
        <div class="flex items-start gap-3">
          <AlertTriangle class="mt-0.5 h-5 w-5 shrink-0 text-rose-700" />
          <div class="min-w-0">
            <p class="font-bold text-rose-900">Diese Punkte blockieren den nächsten Schritt.</p>
            <div class="mt-3 space-y-3">
              <div
                v-for="item in phaseGateway.blockers"
                :key="`${item.label}-${item.to}`"
                class="rounded-2xl border border-rose-100 bg-white/90 p-3"
              >
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0">
                    <p class="text-sm font-semibold text-rose-900">{{ item.label }}</p>
                    <p class="mt-1 text-sm leading-6 text-rose-800">{{ item.detail }}</p>
                    <ul v-if="item.entries?.length" class="mt-2 space-y-1 text-sm text-rose-800">
                      <li v-for="entry in item.entries" :key="`${entry.label}-${entry.to}`" class="truncate">
                        <RouterLink :to="entry.to" class="inline-flex max-w-full items-center gap-1 hover:underline">
                          <span class="shrink-0">•</span>
                          <span class="truncate">{{ entry.label }}</span>
                        </RouterLink>
                      </li>
                    </ul>
                  </div>
                  <RouterLink :to="item.to" class="inline-flex shrink-0 items-center gap-1 rounded-full border border-rose-200 bg-white px-3 py-1.5 text-xs font-semibold text-rose-700 hover:bg-rose-50">
                    Öffnen
                    <ExternalLink class="h-3.5 w-3.5" />
                  </RouterLink>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="phaseGateway.warnings.length" class="rounded-[24px] border border-amber-200 bg-amber-50 p-4">
        <div class="flex items-start gap-3">
          <AlertTriangle class="mt-0.5 h-5 w-5 shrink-0 text-amber-700" />
          <div class="min-w-0">
            <p class="font-bold text-amber-900">Diese Punkte solltest du bewusst prüfen.</p>
            <div class="mt-3 space-y-3">
              <div
                v-for="item in phaseGateway.warnings"
                :key="`${item.label}-${item.to}`"
                class="rounded-2xl border border-amber-100 bg-white/90 p-3"
              >
                <div class="flex items-start justify-between gap-3">
                  <div class="min-w-0">
                    <p class="text-sm font-semibold text-amber-900">{{ item.label }}</p>
                    <p class="mt-1 text-sm leading-6 text-amber-800">{{ item.detail }}</p>
                    <ul v-if="item.entries?.length" class="mt-2 space-y-1 text-sm text-amber-800">
                      <li v-for="entry in item.entries" :key="`${entry.label}-${entry.to}`" class="truncate">
                        <RouterLink :to="entry.to" class="inline-flex max-w-full items-center gap-1 hover:underline">
                          <span class="shrink-0">•</span>
                          <span class="truncate">{{ entry.label }}</span>
                        </RouterLink>
                      </li>
                    </ul>
                  </div>
                  <RouterLink :to="item.to" class="inline-flex shrink-0 items-center gap-1 rounded-full border border-amber-200 bg-white px-3 py-1.5 text-xs font-semibold text-amber-700 hover:bg-amber-50">
                    Öffnen
                    <ExternalLink class="h-3.5 w-3.5" />
                  </RouterLink>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="grid gap-3 rounded-[22px] border border-violet-100 bg-white/80 p-4 text-sm">
        <div class="flex items-center justify-between gap-4">
          <span class="font-semibold text-slate-500">Zielphase</span>
          <strong class="text-right text-slate-900">{{ phaseGateway.phase }}</strong>
        </div>
        <div class="flex items-center justify-between gap-4">
          <span class="font-semibold text-slate-500">Blocker</span>
          <strong class="text-right text-slate-900">{{ phaseGateway.blockers.length }}</strong>
        </div>
        <div class="flex items-center justify-between gap-4">
          <span class="font-semibold text-slate-500">Warnungen</span>
          <strong class="text-right text-slate-900">{{ phaseGateway.warnings.length }}</strong>
        </div>
      </div>
    </div>
    <template #footer>
      <Button type="button" variant="ghost" :disabled="saving || completing" @click="phaseGateway = null">
        Schließen
      </Button>
      <Button
        type="button"
        variant="secondary"
        :disabled="saving || completing || (phaseGateway?.blockers?.length ?? 0) > 0"
        @click="confirmPhaseGateway"
      >
        {{ phaseGateway?.confirmsLabel || 'Fortfahren' }}
      </Button>
    </template>
  </Modal>
</template>
