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 useFetchEvents from "@hooks/useFetchEvents";
import EventPageView from "@views/EventPage/EventPageView";
import PageWrapper from "@views/common/PageWrapper";
import LoadingView from "@views/common/LoadingView";
import NotFoundPage from "@pages/404";

interface InitialProps {
  initialEvent: Event;
}

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

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { data, error } = useFetchEvents({ initialData: initialEvent, id: id as string });

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

  if (!data) {
    return (
      <NotFoundPage />
    );
  }

  return (
    <>
      <Head>
        <link rel="canonical" href={`${process.env.NEXT_PUBLIC_SITE_URL}/events/${id}`} />
      </Head>
      <PageWrapper>
        <EventPageView event={data as 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 initialEvent: Event;
  try {
    initialEvent = await EventApi.getEvent(Number(id));
  } catch (err) {
    notFound = true;
  }
  return {
    props: {
      initialEvent,
    },
    revalidate: 10,
    notFound,
  };
};

export default EventPage;
