import fs from "fs";
import matter from "gray-matter";
import BlogContent from "@/sections/BlogContent";
import Link from "next/link";
import Image from "next/image";
import xButton from "@/images/icon-x.svg";
import getPostMetadata from "@/utils/getPostMetaData";
import { headers } from "next/headers";
import React from "react";

const getPostContent = (slug: string) => {
  const folder = "blogs/";
  const file = `${folder}${slug}.md`;
  const content = fs.readFileSync(file, "utf8");
  const matterResult = matter(content);
  return matterResult;
};

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}) {
  const { slug } = params;
  const headersList = headers();
  const siteURL = headersList.get("host");
  const post = getPostContent(slug);

  return {
    title: `${post.data.title}`,
    description: `${post.data.subtitle}`,
    alternates: {
      canonical: `https://${siteURL}/blogs/${slug}`,
    },
  };
}

export const generateStaticParams = async () => {
  const posts = getPostMetadata();
  return posts.map((post) => ({
    slug: post.slug,
  }));
};

const PostPage = (props: any) => {
  const slug = props.params.slug;
  const post = getPostContent(slug);
  const showModal = props.searchParams?.modal;
  return (
    <>
      {showModal ? (
        <div className="relative bg-grey-950 w-full h-max z-40 py-24 px-6 flex justify-center pointer-events-none">
          <div className="p-8 bg-gray-100 dark:bg-pink-900 w-full max-w-[700px] rounded-xl z-50 relative pointer-events-auto">
            <div className="flex justify-between w-full">
              <Link href="/blogs" className="text-pink-default">
                ← Back to Blogs
              </Link>
              <div className="flex justify-end pb-2 select-none">
                <Link href="/blogs">
                  <Image
                    className="rounded-full p-1 hover:bg-gray-500"
                    src={xButton}
                    alt="close button"
                  />
                </Link>
              </div>
            </div>
            <div className="my-6 md:my-12 border-b border-gray-600 pb-2">
              <BlogContent post={post} />
            </div>
          </div>
        </div>
      ) : (
        <div className="p-8 bg-grey-950">
          <div className="max-w-5xl mx-auto mb-24 h-full w-full py-12 px-8 pt-32">
            <BlogContent post={post} />
          </div>
        </div>
      )}
    </>
  );
};

export default PostPage;
