import { fetchEvents } from '@/fetch/events'
import { PageHeader } from '@/compositions/PageHeader/PageHeader'
import { Section } from '@/components/Section/Section'
import { Container } from '@/components/Container/Container'
import { Title } from '@/components/Title/Title'
import { NextPrevButtons } from '@/components/NextPrevButtons/NextPrevButtons'
import moment from 'moment'
import { transformEvents } from '@/utils/dto/events'
import { weekNumber } from '@/utils/week'
import { EventRow } from '@/components/EventRow/EventRow'
import { fetchHighlightsBetweenDates } from '@/fetch/highlights'
import { Row } from '@/components/Flex/Row'
import { Col } from '@/components/Flex/Col'
import { highlightLink } from '@/utils/dto/highlight'
import Error from '@/pages/_error'


export default async function EventsPage({searchParams}: {
  searchParams: Promise<{ week: string | undefined }>
}) {

  const query = await searchParams;
  const limit = 100;
  let week = query.week;
  if (!week) {
      week = weekNumber(moment());
  }

  const fromDate = moment(week, true);

  if (!fromDate.isValid()) {
    return <Error statusCode={422} message={"Woche fehlerhaft formatiert."}/>
  }

  const toDate = moment(week).add(1, 'week');
  const lastWeek = moment(week).subtract(1, 'week');

  const paginatedEvents = await fetchEvents(
    {
      limit: limit,
      fromDate: fromDate.toDate(),
      toDate: toDate.toDate()
    }
  );

  const paginatedHighlights = ((await fetchHighlightsBetweenDates(
    fromDate.toDate(),
    toDate.toDate(),
  ))?.docs) || [];

  if (!paginatedEvents) {
    return <Error statusCode={503} message={"Veranstaltungen konnten nicht geladen werden."}/>;
  }

  const events = transformEvents(paginatedEvents.docs)

  return (
    <>
      <PageHeader
        title={"Veranstaltungen"}
        description={"Entdecken Sie unsere kommenden Veranstaltungen und seien Sie dabei! Hier finden Sie alle Termine, Informationen und Highlights auf einen Blick."}
      />

      <Section padding={"small"} paddingBottom={"large"}>
        <Container>

          <Row>
            <Col>
              <Title
                color={"contrast"}
                title={`Woche ${week.substring(5)} - ${week.substring(0, 4)}`}
                size={"md"}
              />

              {events.map(e =>
                <EventRow
                  key={e.id}
                  date={e.date}
                  title={e.title}
                  href={e.href}
                  location={e.location}
                  cancelled={e.cancelled}
                />
              )}

              {events.length == 0 &&
                <p>
                  Keine Veranstaltungen gefunden
                </p>
              }
            </Col>
            <Col>
              { paginatedHighlights.length > 0 &&
                <>
                  <Title
                    color={"base"}
                    title={`Highlights`}
                    size={"md"}
                  />

                  { paginatedHighlights.map(h =>
                    <EventRow
                      key={h.id}
                      date={h.date}
                      title={h.text}
                      href={highlightLink(h)}
                      cancelled={false}
                      showDate={false}
                    />
                  )}
                </>

              }

            </Col>
          </Row>
        </Container>
      </Section>

      <Section padding={"small"}>
        <NextPrevButtons
          prev={{
            href: `/veranstaltungen?week=${weekNumber(lastWeek)}`,
            text: "Vorige Woche"
          }}
          next={{
            href: `/veranstaltungen?week=${weekNumber(toDate)}`,
            text: "Nächste Woche"
          }}
        />
      </Section>
    </>
  )
}