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 { PostHeader } from "../../components/PostHeader";
import { readingTime } from "../../utils/general";
import { StyledMarkdown } from "../../components/StyledMarkdown";

export const BlogArticle = ({ frontMatter, html }: MarkdownRenderingResult) => {
  return (
    <MainLayout>
      <div className="rounded-md border border-gray-200 shadow-md shadow-gray-200 dark:shadow-gray-900 dark:border-gray-700 gap-4 bg-black bg-opacity-30 round">
        <div className="mx-10 mt-5 mb-10">
          <Link href="/blog">
            <button className="flex flex-row items-center gap-2 text-primary hover:text-primary-dark dark:text-secondary dark:hover:text-secondary/50 transition-all ease-in duration-75">
              <BackIcon />
              <span>Go Back</span>
            </button>
          </Link>
          <PostHeader frontMatter={frontMatter} estTime={readingTime(html)} />
          <StyledMarkdown html={html} />
        </div>
      </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;
