import React, { Suspense } from "react";

const LazyMarkdown = React.lazy(() => import("react-markdown"));

export function StylizedText({
    children,
    markdown = false,
    mapParagraphToSpan = false,
}: {
    children?: string;
    markdown?: boolean;
    mapParagraphToSpan?: boolean;
}) {
    let str = children;
    if (str === undefined || str === null) {
        return null;
    }
    if (markdown) {
        // Compatibility with old string format
        //These tags are listed in OMConfigComponent.tsx: OMEdit
        str = str.replaceAll(/(\\r\\n)|(\\n)|(<br\/>)|(<br>)/g, "\n\n");
        str = str.replaceAll(/<a href="(.*?)">(.*?)<\/a>/gs, "[$2]($1)");
        str = str.replaceAll(/<a href=(.*?)>(.*?)<\/a>/gs, "[$2]($1)");
        str = str.replaceAll(/<b>(.*?)<\/b>/gs, "**$1**");
        str = str.replaceAll(/<strong>(.*?)<\/strong>/gs, "**$1**");
        str = str.replaceAll(/<p>(.*?)<\/p>/gs, "$1\n\n");
        str = str.replaceAll(/<!--(.*?)-->/gs, "");

        // first test if there is any markdown in the string at all
        // markdown rendering is expensive (~1ms per Component) so we want to avoid it if possible
        // this is a very simple test and will not catch all cases, but it will never give a false positive
        if (!str.match(/[*#[\]\d(`>-]/)) {
            if (mapParagraphToSpan)
                return str.split("\n\n").map((line, index) => <span key={index}>{line}</span>);
            return str.split("\n\n").map((line, index) => <p key={index}>{line}</p>);
        }

        return (
            <Suspense fallback={str}>
                <LazyMarkdown
                    remarkPlugins={[]}
                    components={mapParagraphToSpan ? { p: "span" } : {}}
                >
                    {str}
                </LazyMarkdown>
            </Suspense>
        );
    }
    str = str.replaceAll(/(\\r\\n)|(\\n)/g, " \n");

    return str!.split("\n").map((line, index) => <span key={index}>{line}</span>);
}