import { fetchUpcomingOccurrences } from '@/fetch/eventOccurrences'
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 { transformOccurrences } 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 '@/components/Error/Error'
import { AdminMenu } from '@/components/AdminMenu/AdminMenu'
import { isAuthenticated } from '@/utils/auth'


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

  const authenticated = await isAuthenticated();
  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 paginatedOccurrences = await fetchUpcomingOccurrences(
    {
      limit: limit,
      fromDate: fromDate.toDate(),
      toDate: toDate.toDate()
    }
  );

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

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

  const events = transformOccurrences(paginatedOccurrences.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}
                  end={e.end}
                  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>
      <AdminMenu
        collection={"event"}
        isAuthenticated={authenticated}
      />

      {/*prevents bots indexing till infinity*/}
      { events.length > 0 &&
        <Section padding={"small"}>
          <NextPrevButtons
            prev={{
              href: `/veranstaltungen?week=${weekNumber(lastWeek)}`,
              text: "Vorige Woche"
            }}
            next={{
              href: `/veranstaltungen?week=${weekNumber(toDate)}`,
              text: "Nächste Woche"
            }}
          />
        </Section>
      }
    </>
  )
}