import React, { ComponentProps, RefObject } from "react";
import { twMerge } from "tailwind-merge";
import { serialize } from "next-mdx-remote/serialize";
import remarkGfm from "remark-gfm";
import rehypePrismPlus from "rehype-prism-plus";
import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
import Border from "../../elements/Border";
import { useMDXComponents } from "../mdx-components";
import EmptyContent from "../../elements/EmptyContent";

type Props = {
    value: string;
    maxHeight: string;
    wrapperProps?: ComponentProps<typeof Border>;
};

export default function MarkdownEditorPreviewComponent({
    value,
    maxHeight,
    wrapperProps,
}: Props) {
    try {
        const [mdxSource, setMdxSource] =
            React.useState<
                MDXRemoteSerializeResult<
                    Record<string, unknown>,
                    Record<string, unknown>
                >
            >();

        const { components } = useMDXComponents();

        React.useEffect(() => {
            try {
                // const { data, content } = matter(value);

                const parsedValue = value
                    .replace(/---([^(---)]+)---/, "")
                    .trim();

                serialize(parsedValue, {
                    mdxOptions: {
                        remarkPlugins: [remarkGfm],
                        rehypePlugins: [rehypePrismPlus],
                    },
                    // scope: data,
                })
                    .then((mdxSrc) => {
                        setMdxSource(mdxSrc);
                    })
                    .catch((err) => {});
            } catch (error) {}
        }, [value]);

        return (
            <Border
                {...wrapperProps}
                className={twMerge(
                    `w-full max-h-[${maxHeight}] h-[${maxHeight}] block px-6 pb-10`,
                    "overflow-auto",
                    wrapperProps?.className
                )}
            >
                {mdxSource ? (
                    <MDXRemote
                        {...mdxSource}
                        components={{
                            ...components,
                        }}
                    />
                ) : null}
            </Border>
        );
    } catch (error) {
        return <EmptyContent title={`Markdown Syntax Error.`} />;
    }
}
