'use client'

import type { SelectFieldClientComponent } from 'payload'
import { SelectField, useFormFields } from '@payloadcms/ui'

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

// We clamp 5th-occurrence dates (e.g. the 5th Monday of March) to "4." to
// match the clamp in src/jobs/lib/eventRecurrence.ts (weekOfMonthOf). The
// label and the generated rule must agree on which occurrence the event
// represents.
const weekOfMonthOrdinal = (d: Date): number => Math.min(Math.ceil(d.getDate() / 7), 4)

const parseDate = (raw: unknown): Date | null => {
  if (!raw || typeof raw !== 'string') return null
  const d = new Date(raw)
  return Number.isNaN(d.getTime()) ? null : d
}

export const RecurrenceTypeField: SelectFieldClientComponent = (props) => {
  const dateValue = useFormFields(([fields]) => fields?.date?.value)
  const d = parseDate(dateValue)

  const byDateLabel = d
    ? `Monatlich am ${d.getDate()}.`
    : 'Monatlich (Kalendertag)'
  const byWeekdayLabel = d
    ? `Monatlich am ${weekOfMonthOrdinal(d)}. ${WEEKDAYS_DE[d.getDay()]}`
    : 'Monatlich (n-ter Wochentag)'

  const field = {
    ...props.field,
    options: [
      { label: 'Einmalig', value: 'none' },
      { label: 'Täglich', value: 'daily' },
      { label: 'Wöchentlich', value: 'weekly' },
      { label: 'Alle 2 Wochen', value: 'biweekly' },
      { label: byDateLabel, value: 'monthlyByDate' },
      { label: byWeekdayLabel, value: 'monthlyByWeekday' },
      { label: 'Benutzerdefiniert (mehrere Regeln)', value: 'custom' },
    ],
  }

  return <SelectField {...props} field={field} />
}

export default RecurrenceTypeField