import { GetStaticPaths, GetStaticProps } from "next";
import fs from "fs";
import { ParsedUrlQuery } from "querystring";
import { getProjectContentBySlug, PROJECTS_PATH } from "../../utils/markdown";
import { MarkdownRenderingResult } from "../../types/types";
import { MainLayout } from "../../layouts/MainLayout";
import Link from "next/link";
import { IoMdArrowRoundBack as BackIcon } from "react-icons/io";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { readingTime } from "../../utils/general";
import { MarkdownComponents } from "../../utils/reactmarkdown";
import { PostHeader } from "../../components/PostHeader";

export const ProjectArticle = ({
  frontMatter,
  html,
}: MarkdownRenderingResult) => {
  return (
    <MainLayout>
      <Link href="/projects">
        <button className="flex flex-row items-center gap-2 text-secondary hover:text-secondary/50 transition-all ease-in duration-75">
          <BackIcon />
          <span>Go Back</span>
        </button>
      </Link>

      <PostHeader frontMatter={frontMatter} estTime={readingTime(html)} />
      <div
        className="
        prose prose-code:font-mono prose-code:text-gray-100 prose-code:bg-gray-700 
        prose-code:p-1 prose-code:m-1 prose-code:rounded-md prose-headings:text-primary-text 
      prose-p:text-gray-100 prose-img:w-full prose-img:h-auto xl:prose-img:max-h-96 
      prose-img:object-cover prose-li:text-gray-300 prose-td:text-gray-400 
      prose-a:text-action prose-strong:text-gray-50"
      >
        <ReactMarkdown
          components={MarkdownComponents}
          remarkPlugins={[remarkGfm]}
          children={html}
        />
      </div>
    </MainLayout>
  );
};
interface ProjectProps extends ParsedUrlQuery {
  slug: string;
}
export const getStaticPaths: GetStaticPaths<ProjectProps> = async () => {
  const paths = fs
    .readdirSync(PROJECTS_PATH)
    .map((path) => path.replace(/\.mdx?$/, ""))
    .map((slug) => ({ params: { slug } }));

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

export const getStaticProps: GetStaticProps<MarkdownRenderingResult> = async ({
  params,
}) => {
  const markdownContent = getProjectContentBySlug(params?.slug as string);
  return {
    props: {
      frontMatter: markdownContent.frontMatter,
      html: markdownContent.content,
    },
  };
};
export default ProjectArticle;
