import type { Event } from '@/payload-types'

const WEEKDAYS_DE = [
  'Sonntag',
  'Montag',
  'Dienstag',
  'Mittwoch',
  'Donnerstag',
  'Freitag',
  'Samstag',
]

const WEEKDAY_LABEL: Record<string, string> = {
  monday: 'Montag',
  tuesday: 'Dienstag',
  wednesday: 'Mittwoch',
  thursday: 'Donnerstag',
  friday: 'Freitag',
  saturday: 'Samstag',
  sunday: 'Sonntag',
}

const WEEK_OF_MONTH_LABEL: Record<string, string> = {
  first: '1.',
  second: '2.',
  third: '3.',
  fourth: '4.',
  last: 'letzten',
}

// Match the clamp in eventRecurrence.ts so the label on the Event page
// agrees with the rule the generator actually produces.
const weekOfMonthN = (d: Date): number => Math.min(Math.ceil(d.getDate() / 7), 4)

const formatTime = (d: Date): string => {
  const hh = String(d.getHours()).padStart(2, '0')
  const mm = String(d.getMinutes()).padStart(2, '0')
  return `${hh}:${mm}`
}

const withTime = (description: string, d: Date | null): string =>
  d ? `${description} um ${formatTime(d)} Uhr` : description

type RecurrenceRule = NonNullable<Event['recurrenceRules']>[number]

const describeCustomRule = (rule: RecurrenceRule): string | null => {
  switch (rule.frequency) {
    case 'daily':
      return 'Täglich'
    case 'weekly': {
      const weekday = rule.weekday ? WEEKDAY_LABEL[rule.weekday] : null
      return weekday ? `Jeden ${weekday}` : null
    }
    case 'monthlyByDate':
      return typeof rule.dayOfMonth === 'number'
        ? `Am ${rule.dayOfMonth}. jedes Monats`
        : null
    case 'monthlyByWeekday': {
      const weekday = rule.weekday ? WEEKDAY_LABEL[rule.weekday] : null
      const week = rule.weekOfMonth ? WEEK_OF_MONTH_LABEL[rule.weekOfMonth] : null
      return weekday && week ? `Am ${week} ${weekday} jedes Monats` : null
    }
    default:
      return null
  }
}

/**
 * Human-readable German description of an event's recurrence. Returns
 * `undefined` for one-shot events (recurrenceType = 'none' / missing) so
 * callers can fall back to a regular date.
 */
export const describeRecurrence = (
  event: Pick<Event, 'recurrenceType' | 'recurrenceRules' | 'date'>,
): string | undefined => {
  const type = event.recurrenceType
  if (!type || type === 'none') return undefined

  const parsed = event.date ? new Date(event.date) : null
  const d = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null

  switch (type) {
    case 'daily':
      return withTime('Täglich', d)
    case 'weekly':
      return withTime(d ? `Jeden ${WEEKDAYS_DE[d.getDay()]}` : 'Wöchentlich', d)
    case 'biweekly':
      return withTime(
        d ? `Alle 2 Wochen, ${WEEKDAYS_DE[d.getDay()]}` : 'Alle 2 Wochen',
        d,
      )
    case 'monthlyByDate':
      return withTime(d ? `Monatlich am ${d.getDate()}.` : 'Monatlich', d)
    case 'monthlyByWeekday':
      return withTime(
        d
          ? `Monatlich am ${weekOfMonthN(d)}. ${WEEKDAYS_DE[d.getDay()]}`
          : 'Monatlich',
        d,
      )
    case 'custom': {
      const rules = event.recurrenceRules ?? []
      const parts = rules
        .map(describeCustomRule)
        .filter((p): p is string => Boolean(p))
      if (parts.length === 0) return withTime('Benutzerdefiniert', d)
      return withTime(parts.join(' · '), d)
    }
    default:
      return undefined
  }
}
