import type { ComponentProps } from 'react'
import { Event, EventOccurrence } from '@/payload-types'
import type { EventPage } from '@/pageComponents/Event/Event'
import { describeRecurrence } from '@/utils/recurrenceDescription'

export const getEventGroupSlug = (event: Event): string | undefined => {
  const firstGroup = event.group?.[0]
  if (typeof firstGroup !== 'object' || firstGroup === null) return undefined
  return firstGroup.slug ?? undefined
}

type EventPageProps = ComponentProps<typeof EventPage>
type EventPagePropsAdapted = Omit<
  EventPageProps,
  'isAuthenticated' | 'upcomingOccurrences' | 'photo'
>

export const eventToPageProps = (
  event: Event,
  occurrence?: EventOccurrence,
): EventPagePropsAdapted => ({
  id: event.id,
  title: event.title,
  date: occurrence?.date ?? event.date,
  endDateTime: occurrence?.endDateTime ?? event.endDateTime ?? undefined,
  createdAt: event.createdAt,
  cancelled: Boolean(event.cancelled || occurrence?.cancelled),
  recurrenceType: event.recurrenceType,
  // Only describe recurrence on the event page itself; the occurrence
  // page shows that occurrence's concrete date.
  recurrenceDescription: occurrence ? undefined : describeRecurrence(event),
  location: event.location,
  description: event.description,
  shortDescription: event.shortDescription,
  group: getEventGroupSlug(event),
  contact: event.contact || undefined,
  rsvpLink: event.rsvpLink || undefined,
  flyer: typeof event.flyer === 'object' ? event.flyer || undefined : undefined,
})

type EventRowItem = {
  id: string
  date: string
  end?: string
  title: string
  href: string
  location: string
  cancelled: boolean
}

export const transformOccurrences = (
  occurrences: EventOccurrence[],
): EventRowItem[] => {
  return occurrences
    .map((o): EventRowItem | undefined => {
      const event = typeof o.event === 'object' ? o.event : undefined
      if (!event) return undefined
      return {
        id: o.id,
        title: event.title,
        date: o.date,
        end: o.endDateTime ?? undefined,
        href: `/veranstaltungen/${event.id}/${o.id}`,
        location: typeof event.location === 'object' ? event.location.name : 'Unbekannt',
        cancelled: Boolean(event.cancelled || o.cancelled),
      }
    })
    .filter((x): x is EventRowItem => Boolean(x))
}

/**
 * Legacy mapper kept for any caller still working with bare Event docs.
 * New code should prefer `transformOccurrences`.
 */
export const transformEvents = (events: Event[]): EventRowItem[] => {
  return events.map((e) => ({
    id: e.id,
    title: e.title,
    date: e.date,
    end: e.endDateTime ?? undefined,
    href: `/veranstaltungen/${e.id}`,
    location: typeof e.location === 'object' ? e.location.name : 'Unbekannt',
    cancelled: e.cancelled,
  }))
}
