import { ParsedUrlQuery } from "querystring";

import { GetStaticPaths, GetStaticProps } from "next";
import { MDXRemote } from "next-mdx-remote";
import React from "react";

import { EventCard } from "@/components/EventCard";
import { Title } from "@/components/Title";
import {
  Event,
  getEventYears,
  getEventTermsByYear,
  getEventsByTerm,
  getEventBySlug,
} from "@/lib/events";
import { capitalize } from "@/utils";

export default function EventInfoPage({ year, term, event }: Props) {
  return (
    <>
      <Title>{[event.metadata.name, `${capitalize(term)} ${year}`]}</Title>
      <EventCard
        {...event.metadata}
        date={new Date(event.metadata.date)}
        showDescription
      >
        <MDXRemote {...event.content} />
      </EventCard>
    </>
  );
}

interface Props {
  year: string;
  term: string;
  event: Event;
}

interface Params extends ParsedUrlQuery {
  year: string;
  term: string;
  event: string;
}

export const getStaticProps: GetStaticProps<Props, Params> = async (
  context
) => {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const { year, term, event } = context.params!;
  return {
    props: { year, term, event: await getEventBySlug(year, term, event) },
  };
};

export const getStaticPaths: GetStaticPaths<Params> = async () => {
  const years = await getEventYears();
  const events = (
    await Promise.all(
      years.map(async (year) => {
        const termsInYear = await getEventTermsByYear(year);
        return await Promise.all(
          termsInYear.map(async (term) => {
            const eventsInTerm = await getEventsByTerm(year, term);
            return eventsInTerm.map((event) => ({
              year,
              term,
              event,
            }));
          })
        );
      })
    )
  ).flat(2);

  return {
    paths: events.map((params) => ({ params })),
    fallback: false,
  };
};
