import React from "react";
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 { useMDXComponents } from "../mdx/mdx-components";

export const TWUIPrismLanguages = ["shell", "javascript"] as const;

type Props = {
    content: string;
    refresh?: number;
};

/**
 * # CodeBlock
 *
 * @className `twui-remote-code-block-wrapper`
 */
export default function RemoteCodeBlock({ content, refresh }: Props) {
    const [mdxSource, setMdxSource] =
        React.useState<MDXRemoteSerializeResult<any>>();

    const { components } = useMDXComponents();

    React.useEffect(() => {
        serialize(content, {
            mdxOptions: {
                remarkPlugins: [remarkGfm],
                rehypePlugins: [rehypePrismPlus],
            },
        }).then((mdxSrc) => {
            setMdxSource(mdxSrc);
        });
    }, [refresh]);

    if (!mdxSource) {
        return null;
    }

    return (
        <MDXRemote
            {...mdxSource}
            components={{
                ...components,
            }}
        />
    );
}
