import { GetStaticPaths, GetStaticProps } from "next";
import fs from "fs";
import { ParsedUrlQuery } from "querystring";
import { BLOGS_PATH, getBlogContentBySlug } 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 { MarkdownComponents } from "../../utils/reactmarkdown";
import remarkGfm from "remark-gfm";
import { PostHeader } from "../../components/PostHeader";
import { readingTime } from "../../utils/general";

export const BlogArticle = ({ frontMatter, html }: MarkdownRenderingResult) => {
  return (
    <MainLayout>
      <Link href="/blog">
        <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 BlogProps extends ParsedUrlQuery {
  slug: string;
}
export const getStaticPaths: GetStaticPaths<BlogProps> = async () => {
  const paths = fs
    .readdirSync(BLOGS_PATH)
    .map((path) => path.replace(/\.mdx?$/, ""))
    .map((slug) => ({ params: { slug } }));

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

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