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 { MiniEventCard } from "@/components/MiniEventCard";
import {
  getEventYears,
  getEventTermsByYear,
  getEventsByTerm,
  getEventBySlug,
  Event,
} from "@/lib/events";

import styles from "./term.module.css";

interface Props {
  term: string;
  year: string;
  pastEvents: Event[];
  futureEvents: Event[];
}

export default function Term(props: Props) {
  const hasPastEvents = props.pastEvents.length !== 0;
  const hasFutureEvents = props.futureEvents.length !== 0;

  return (
    <div className={styles.main}>
      {hasFutureEvents && (
        <>
          <h2 className={styles.heading2}>Upcoming Events:</h2>
          <hr />
          <div className={styles.miniEventCards}>
            {props.futureEvents.map(({ content, metadata }) => (
              <EventCard
                {...metadata}
                date={new Date(metadata.date)}
                key={metadata.name + metadata.date.toString()}
              >
                <MDXRemote {...content} />
              </EventCard>
            ))}
          </div>
        </>
      )}
      {hasFutureEvents && hasPastEvents && (
        <>
          <h2 className={styles.heading2}>Past Events:</h2>
          <hr />
        </>
      )}
      {!hasFutureEvents && (
        <>
          <h2 className={styles.heading2}>
            Events Archive:
            <span className={styles.blue}>
              {` ${props.term.charAt(0).toUpperCase()}${props.term.slice(1)} ${
                props.year
              }`}
            </span>
          </h2>
          <hr />
        </>
      )}
      <div className={styles.miniEventCards}>
        {props.pastEvents.map(({ content, metadata }) => (
          <MiniEventCard
            {...metadata}
            date={new Date(metadata.date)}
            description={<MDXRemote {...content} />}
            key={metadata.name + metadata.date.toString()}
          />
        ))}
      </div>
    </div>
  );
}

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

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

  const eventNames = await getEventsByTerm(year, term);

  const events: Event[] = (
    await Promise.all(
      eventNames.map((file: string) => getEventBySlug(year, term, file))
    )
  ).sort(
    (a, b) =>
      new Date(a.metadata.date).getTime() - new Date(b.metadata.date).getTime()
  );

  const pastEvents = events.filter(
    (event) => new Date(event.metadata.date).getTime() < Date.now()
  );

  const futureEvents = events.filter(
    (event) => new Date(event.metadata.date).getTime() >= Date.now()
  );

  return {
    props: {
      term: term,
      year: year,
      pastEvents: pastEvents,
      futureEvents: futureEvents,
    },
  };
};

export const getStaticPaths: GetStaticPaths<Params> = async () => {
  const years = await getEventYears();
  const paths = [];
  for (const year of years) {
    const terms = await getEventTermsByYear(year);
    const yearPaths = terms.map((curTerm) => ({
      params: { year: year, term: curTerm },
    }));
    paths.push(...yearPaths);
  }

  return {
    paths: paths,
    fallback: false,
  };
};
