import RenderWithoutJS from "@/components/RenderWithoutJS";
import Sidebar from "@/components/Sidebar";
import index from "@/styles/Index.module.sass"
import { remark } from "remark"
import remarkFrontmatter from "remark-frontmatter"
import { read } from "to-vfile"
import listFiles from "@/lib/listFiles";
import Markdown from 'markdown-to-jsx';
import Link from "@/components/Link";
import Image from "@/components/Image";
import Head from "next/head";
import matter from "gray-matter";
import getFrontmatter from "@/lib/getFrontmatter";
// import post from ""
const Post = (props: { post: string, slug: string, matter: any }) => {

    function title() {
        if(!props.matter) return `lio's blog`
        else return `${props.matter.title} | lio's blog`
    }

    return (
        <RenderWithoutJS>
            <main id={index.layout}>
                <Head>
                    <title>{title()}</title>
                </Head>
                <Sidebar />
                <section id={index.main}>
                    <Markdown
                        children={props.post}
                        options={{
                            overrides: {
                                a: ({ ...props }) => <Link href={props.href} title={props.children} withArrow />,
                                img: ({ ...props }) => <Image src={props.src} alt={props.alt} />,
                                p: ({ children, ...props }) => {
                                    const ParaComponent = children[0]?.type?.name === 'img' ? 'div' : 'p'
                                    return <ParaComponent {...props}>{children}</ParaComponent>
                                },
                            }
                        }}
                    />
                </section>
            </main>
        </RenderWithoutJS>
    );

};

export default Post

export async function getStaticProps(context: any) {
    let post = matter(await (await read(`${listFiles('./src/blog').find(file => file.includes(context.params.slug))}`)).value)
    return {
        props: {
            post: (post.content as string).replace(/^(---)\n*([a-zA-Z0-9\/\#[\]\"_:,\-\s*]*)(---)$/mi, ""),
            matter: post.data,
            slug: context.params.slug
        }
    }
}


export async function getStaticPaths() {
    let path = './src/blog'
    let paths = listFiles(path).map(file => file.replace(path, "/blog").replace(/.mdx?/gmi, ''))
    return {
        paths,
        fallback: true
    }
}