<template>
  <Card class="overflow-hidden">
    <div class="border-b border-violet-100 bg-gradient-to-br from-white via-violet-50/70 to-[#f7eef8] p-5">
      <div class="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <p class="text-xs font-semibold uppercase tracking-[0.24em] text-violet-500">{{ props.form.year || '-' }} · Timeline</p>
          <h2 class="mt-1 text-xl font-bold leading-tight text-slate-900">Phasen und Pausen bearbeiten</h2>
          <p class="mt-2 max-w-2xl text-sm leading-5 text-slate-500">
            Pflege die echten Zeitfenster für Landingpage, Public-API und Teilnahme-Gates. Die Aufbereitung ist die planbare Pause zwischen Voting und Show.
          </p>
        </div>
        <span class="w-fit rounded-full border border-violet-200 bg-white px-4 py-2 text-sm font-bold text-violet-700">
          {{ props.form.currentPhase || 'Keine Phase gesetzt' }}
        </span>
      </div>
    </div>

    <p v-if="timelineError" class="border-b border-rose-100 bg-rose-50 px-6 py-3 text-sm font-semibold text-rose-700" role="alert">{{ timelineError }}</p>

    <div class="hidden grid-cols-[34px_minmax(0,1fr)_240px_128px_110px] gap-4 border-b border-violet-100 bg-violet-50/50 px-5 py-3 text-[11px] font-bold uppercase tracking-[0.16em] text-violet-500 lg:grid">
      <span></span>
      <span>Phase</span>
      <span>Zeitraum</span>
      <span>Status</span>
      <span class="text-right">Bearbeiten</span>
    </div>

    <div class="max-h-[390px] overflow-y-auto divide-y divide-violet-50">
      <div
        v-for="row in timelineRows"
        :key="row.key"
        class="grid gap-4 px-5 py-3.5 lg:grid-cols-[34px_minmax(0,1fr)_240px_128px_110px] lg:items-center"
        :class="row.isEditing ? 'bg-violet-50/50' : 'bg-white/70'"
      >
        <span class="mt-2 h-2.5 w-2.5 rounded-full lg:mx-auto lg:mt-0" :class="row.dotClass"></span>

        <div class="min-w-0">
          <p class="font-semibold text-slate-900">{{ row.title }}</p>
          <p class="mt-1 text-sm leading-5 text-slate-500">{{ row.description }}</p>
        </div>

        <div v-if="row.isEditing" class="grid gap-2">
          <template v-if="row.key === 'show'">
            <input v-model="draft.start" type="date" class="h-10 rounded-xl border border-violet-200 bg-white px-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" />
            <input v-model="draft.showStartsAt" type="time" class="h-10 rounded-xl border border-violet-200 bg-white px-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" />
          </template>
          <template v-else>
            <div class="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-2">
              <input v-model="draft.start" type="date" class="h-10 min-w-0 rounded-xl border border-violet-200 bg-white px-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" />
              <input v-model="draft.end" type="date" class="h-10 min-w-0 rounded-xl border border-violet-200 bg-white px-3 text-sm outline-none transition focus:border-violet-400 focus:ring-4 focus:ring-violet-100" />
            </div>
          </template>
        </div>
        <p v-else class="text-sm font-semibold text-slate-600">{{ row.dateRange }}</p>

        <span class="w-fit rounded-full border px-3 py-1 text-xs font-bold" :class="row.statusClass">
          {{ row.statusLabel }}
        </span>

        <div class="flex flex-wrap justify-start gap-2 lg:justify-end">
          <template v-if="row.isEditing">
            <Button size="sm" :disabled="props.saving" @click="saveTimelineEdit(row)">OK</Button>
            <button
              type="button"
              class="grid h-9 w-9 place-items-center rounded-xl border border-violet-100 bg-white text-slate-500 transition hover:bg-violet-50"
              :disabled="props.saving"
              title="Bearbeitung abbrechen"
              @click="cancelTimelineEdit"
            >
              <X class="h-4 w-4" />
            </button>
          </template>
          <template v-else>
            <button
              v-if="row.editable"
              type="button"
              class="grid h-9 w-9 place-items-center rounded-xl border border-violet-100 bg-white text-violet-700 transition hover:bg-violet-50 disabled:cursor-not-allowed disabled:opacity-50"
              :disabled="props.saving || !props.selectedSeasonId"
              title="Zeitraum bearbeiten"
              @click="startTimelineEdit(row)"
            >
              <Pencil class="h-4 w-4" />
            </button>
            <span v-else class="text-xs font-semibold text-slate-400">fest</span>
          </template>
        </div>
      </div>
    </div>

    <div class="border-t border-violet-100 bg-violet-50/30 px-5 py-3">
      <p class="text-xs leading-5 text-slate-500">
        Hinweis: Nominierung, Voting, Aufbereitung und Show sind als Systemfenster verdrahtet, damit Public-API, Vorschau und Teilnahme-Gates sauber zusammenlaufen.
      </p>
    </div>
  </Card>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Pencil, X } from '@lucide/vue'

import Button from '../ui/Button.vue'
import Card from '../ui/Card.vue'
import {
  createSeasonTimelineRows,
  normalizePhaseKey,
  resolveAutoPhase,
  type PhaseKey,
  type PhaseRowConfig,
  type SeasonTimelineForm,
} from './adminSeasonTimeline'

const props = defineProps<{
  form: SeasonTimelineForm
  saving: boolean
  selectedSeasonId: number | null
  saveSeason: () => Promise<boolean | void> | boolean | void
}>()

const editingPhase = ref<PhaseKey | null>(null)
const timelineError = ref('')
const draft = reactive({
  start: '',
  end: '',
  showStartsAt: '20:00',
})

const currentPhaseKey = computed(() => normalizePhaseKey(props.form.currentPhase))
const autoPhase = computed(() => resolveAutoPhase(props.form))
const timelineRows = computed(() =>
  createSeasonTimelineRows(props.form, currentPhaseKey.value, autoPhase.value, editingPhase.value),
)

function startTimelineEdit(row: PhaseRowConfig) {
  if (!row.editable) return
  timelineError.value = ''
  editingPhase.value = row.key
  draft.start = row.start ? props.form[row.start] : ''
  draft.end = row.end ? props.form[row.end] : ''
  draft.showStartsAt = props.form.showStartsAt || '20:00'
}

function cancelTimelineEdit() {
  editingPhase.value = null
  timelineError.value = ''
}

async function saveTimelineEdit(row: PhaseRowConfig) {
  timelineError.value = ''
  if (!row.start || !row.end) {
    return
  }

  if (!draft.start || !draft.end) {
    timelineError.value = 'Bitte fülle Start und Ende der Phase aus.'
    return
  }

  if (row.key !== 'show' && draft.start > draft.end) {
    timelineError.value = 'Das Startdatum darf nicht nach dem Enddatum liegen.'
    return
  }

  props.form[row.start] = draft.start
  props.form[row.end] = row.key === 'show' ? draft.start : draft.end
  if (row.key === 'show') {
    props.form.showStartsAt = draft.showStartsAt || '20:00'
  }

  const saved = await props.saveSeason()
  if (saved !== false) {
    editingPhase.value = null
  }
}
</script>
