import React from "react";
import { NextPage, GetStaticProps, GetStaticPaths } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import Event from "@models/Event";
import EventApi from "@api/eventApi";
import EventPageView from "@views/EventPage/EventPageView";
import PageWrapper from "@views/common/PageWrapper";
import LoadingView from "@views/common/LoadingView";

interface InitialProps {
  event: Event;
}

const EventPage: NextPage<InitialProps> = ({ event }) => {
  const router = useRouter();
  const { id } = router.query;

  if (router.isFallback) return <LoadingView />;

  return (
    <>
      <Head>
        <link rel="canonical" href={`${process.env.NEXT_PUBLIC_SITE_URL}/events/${id}`} />
      </Head>
      <PageWrapper>
        <EventPageView event={event} />
      </PageWrapper>
    </>
  );
};

export const getStaticPaths: GetStaticPaths = async () => {
  const allEvents = await EventApi.getEvents();
  const paths = allEvents.map((e: Event) => ({
    params: {
      id: String(e.id),
    },
  }
  ));
  return {
    paths,
    fallback: true,
  };
};

export const getStaticProps: GetStaticProps<InitialProps> = async ({ params }) => {
  const { id } = params;
  let notFound = false;
  let event: Event;
  try {
    event = await EventApi.getEvent(Number(id));
  } catch (err) {
    notFound = true;
  }
  return {
    props: {
      event,
    },
    revalidate: 10, // Required for deleting hidden pages
    notFound,
  };
};

export default EventPage;
