import { GetStaticPaths, GetStaticProps } from "next";
import fs from "fs";
import { ParsedUrlQuery } from "querystring";
import {
  BLOGS_PATH,
  getBlogContentBySlug,
  renderMarkdown,
} 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 { BasicBlogProps } from ".";

export const BlogArticle = ({ frontMatter, html }: MarkdownRenderingResult) => {
  const { title, author, date, description, authorLink } =
    frontMatter as BasicBlogProps;
  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>
      <div className="lg:mt-10 mt-4 mb-2 text-sm font-medium text-gray-500">
        {date}
      </div>
      <div className="lg:text-5xl font-bold">{title}</div>
      {author && (
        <div className="mt-2 font-medium">
          By{" "}
          {authorLink && (
            <Link href={authorLink} className="text-action">
              @{author}
            </Link>
          )}
          {!authorLink && <span className="text-action">@{author}</span>}
        </div>
      )}
      <div className="mt-2">{description}</div>
      <div
        className="mt-4 prose prose-headings:text-primary-text prose-p:text-gray-400"
        dangerouslySetInnerHTML={{ __html: html }}
      />
    </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);
  const renderedHTML = await renderMarkdown(markdownContent.content);
  return {
    props: {
      frontMatter: markdownContent.frontMatter,
      html: renderedHTML,
    },
  };
};
export default BlogArticle;
