import { Highlight } from '@/payload-types'
import { fetchUpcomingOccurrences } from '@/fetch/eventOccurrences'
import { fetchHighlights } from '@/fetch/highlights'
import { transformOccurrences } from '@/utils/dto/events'
import { highlightLink } from '@/utils/dto/highlight'
import { Section } from '@/components/Section/Section'
import { Title } from '@/components/Title/Title'
import { EventRow } from '@/components/EventRow/EventRow'
import { Events } from '@/compositions/Events/Events'
import { ContentWithSlider } from '@/compositions/ContentWithSlider/ContentWithSlider'

type EventsBlockProps = {
  title?: string | null
  itemsPerPage?: number | null
}

export async function EventsBlock({
  title = 'Veranstaltungen',
  itemsPerPage = 6,
}: EventsBlockProps) {
  const occurrences = await fetchUpcomingOccurrences({ limit: itemsPerPage || 6 })
  const occurrenceDocs = occurrences?.docs || []

  if (occurrenceDocs.length === 0) return null

  const highlights = await fetchHighlights()
  const highlightDocs = highlights?.docs || []

  return (
    <ContentWithSlider slider={<HighlightsSlider highlights={highlightDocs} />}>
      <Section>
        <Title color={'contrast'} title={title || 'Veranstaltungen'} />
        <Events
          events={transformOccurrences(occurrenceDocs)}
          n={itemsPerPage || 6}
          schema={'contrast'}
        />
      </Section>
    </ContentWithSlider>
  )
}

const HighlightsSlider = ({ highlights }: { highlights: Highlight[] }) => (
  <>
    <Title
      title={'Aktuelle Highlights'}
      size={'md'}
      fontStyle={'sans-serif'}
      color={'white'}
    />
    {highlights.map((highlight) => (
      <EventRow
        color={'white'}
        key={highlight.id}
        date={highlight.date}
        showDate={false}
        title={highlight.text}
        href={highlightLink(highlight)}
        cancelled={false}
      />
    ))}
  </>
)
