import React from "react";
import { NextPage, GetStaticProps, GetStaticPaths } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import Post from "@models/Feed";
import FeedApi from "@api/feedApi";
import useFetchFeed from "@hooks/useFetchFeed";
import FeedPageView from "@views/FeedPage/FeedPageView";
import PageWrapper from "@views/common/PageWrapper";
import LoadingView from "@views/common/LoadingView";
import NotFoundPage from "@pages/404";

interface InitialProps {
  initialPost: Post;
}

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

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { data, error } = useFetchFeed({ initialData: initialPost, 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}/feed/${id}`} />
      </Head>
      <PageWrapper>
        <FeedPageView post={data} />
      </PageWrapper>
    </>
  );
};

export const getStaticPaths: GetStaticPaths = async () => {
  const feed = await FeedApi.getFeed();
  const paths = feed.map((post: Post) => ({
    params: {
      id: String(post.id),
    },
  }
  ));
  return {
    paths,
    fallback: true,
  };
};

export const getStaticProps: GetStaticProps<InitialProps> = async ({ params }) => {
  const { id } = params;
  let notFound = false;
  let initialPost: Post;
  try {
    initialPost = await FeedApi.getPost(Number(id));
  } catch (err) {
    notFound = true;
  }

  return {
    props: {
      initialPost,
    },
    revalidate: 10,
    notFound,
  };
};

export default FeedPage;
