import { normalizeAdminWorkflowPhase, type AdminWorkflowPhaseKey } from './adminReadinessPhase'

export type PhaseKey = AdminWorkflowPhaseKey

export type SeasonDateField =
  | 'nominationStartsAt'
  | 'nominationEndsAt'
  | 'votingStartsAt'
  | 'votingEndsAt'
  | 'reviewStartsAt'
  | 'reviewEndsAt'
  | 'showDate'

export interface SeasonTimelineForm {
  year: number
  currentPhase: string
  nominationStartsAt: string
  nominationEndsAt: string
  votingStartsAt: string
  votingEndsAt: string
  reviewStartsAt: string
  reviewEndsAt: string
  showDate: string
  showStartsAt: string
}

export interface PhaseRowConfig {
  key: PhaseKey
  title: string
  description: string
  start: SeasonDateField | null
  end: SeasonDateField | null
  editable: boolean
}

export interface SeasonTimelineRow extends PhaseRowConfig {
  active: boolean
  isEditing: boolean
  dateRange: string
  statusLabel: string
  dotClass: string
  statusClass: string
}

export const SEASON_PHASES: PhaseRowConfig[] = [
  {
    key: 'nomination',
    title: 'Nominierung',
    description: 'Community reicht Creator-Vorschläge ein.',
    start: 'nominationStartsAt',
    end: 'nominationEndsAt',
    editable: true,
  },
  {
    key: 'voting',
    title: 'Community Voting',
    description: 'Finale Kandidat:innen sind sichtbar und wählbar.',
    start: 'votingStartsAt',
    end: 'votingEndsAt',
    editable: true,
  },
  {
    key: 'preparation',
    title: 'Aufbereitung',
    description: 'Pause vor der Show: Ergebnisse, Clips und Ablauf vorbereiten.',
    start: 'reviewStartsAt',
    end: 'reviewEndsAt',
    editable: true,
  },
  {
    key: 'show',
    title: 'Award Show',
    description: 'Finale Live-Show inklusive Stream-Countdown.',
    start: 'showDate',
    end: 'showDate',
    editable: true,
  },
  {
    key: 'completed',
    title: 'Abgeschlossen',
    description: 'Award-Jahr ist archiviert und Public-Aktionen sind gesperrt.',
    start: null,
    end: null,
    editable: false,
  },
]

export function createSeasonTimelineRows(
  form: SeasonTimelineForm,
  currentPhaseKey: PhaseKey | string,
  autoPhase: string,
  editingPhase: PhaseKey | null,
): SeasonTimelineRow[] {
  return SEASON_PHASES.map((phase) => {
    const active = phase.key === currentPhaseKey
    const isAutoActive = autoPhase === phase.title
    const state = active ? 'active' : resolvePhaseState(form, phase)

    return {
      ...phase,
      active,
      isEditing: editingPhase === phase.key,
      dateRange: formatPhaseRange(form, phase),
      statusLabel: active ? 'Aktiv' : isAutoActive ? 'Auto' : state === 'done' ? 'Erledigt' : 'Geplant',
      dotClass: active ? 'bg-violet-600' : isAutoActive ? 'bg-amber-500' : state === 'done' ? 'bg-emerald-500' : 'bg-slate-300',
      statusClass: active
        ? 'border-violet-200 bg-violet-100 text-violet-800'
        : isAutoActive
          ? 'border-amber-200 bg-amber-50 text-amber-700'
          : state === 'done'
            ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
            : 'border-slate-200 bg-slate-50 text-slate-500',
    }
  })
}

export function normalizePhaseKey(value: string): PhaseKey {
  return normalizeAdminWorkflowPhase(value)
}

export function resolveAutoPhase(form: SeasonTimelineForm) {
  const today = startOfDay(new Date())
  for (const phase of SEASON_PHASES.slice(0, 4)) {
    const start = phase.start ? parseDate(form[phase.start]) : null
    const end = phase.end ? parseDate(form[phase.end]) : null
    if (start && end && start <= today && today <= end) {
      return phase.title
    }
  }

  return hasShowDayPassed(form) ? 'Abgeschlossen' : ''
}

function resolvePhaseState(form: SeasonTimelineForm, phase: PhaseRowConfig) {
  const today = startOfDay(new Date())
  if (phase.key === 'completed') {
    return hasShowDayPassed(form) ? 'done' : 'upcoming'
  }

  const end = phase.end ? parseDate(form[phase.end]) : null
  return end && end < today ? 'done' : 'upcoming'
}

function formatPhaseRange(form: SeasonTimelineForm, phase: PhaseRowConfig) {
  if (phase.key === 'completed') {
    return form.showDate ? `nach ${formatDate(form.showDate)}` : 'nach der Show'
  }

  const start = phase.start ? form[phase.start] : ''
  const end = phase.end ? form[phase.end] : ''
  if (!start && !end) return 'Noch nicht terminiert'
  if (phase.key === 'show') return `${formatDate(start)} · ${form.showStartsAt || '20:00'} Uhr`
  if (start === end) return formatDate(start)
  return `${formatDate(start)} - ${formatDate(end)}`
}

function parseDate(value: string) {
  if (!value) return null
  const date = startOfDay(new Date(`${value}T00:00:00`))
  return Number.isNaN(date.getTime()) ? null : date
}

export function hasShowDayPassed(form: Pick<SeasonTimelineForm, 'showDate'>) {
  const showDate = parseDate(form.showDate)
  return Boolean(showDate && startOfDay(new Date()) > showDate)
}

function startOfDay(date: Date) {
  const next = new Date(date)
  next.setHours(0, 0, 0, 0)
  return next
}

function formatDate(value: string) {
  if (!value) return 'offen'
  const date = parseDate(value)
  return date
    ? date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
    : value
}
