import React, { ReactNode } from "react";
import classNames from "classnames";
import ReactMarkdown, { ReactMarkdownProps } from "react-markdown";
import { bem } from "../../utilities/bem";
import { Text } from "../Text";

const cn = "Markdown";

export interface MarkdownProps extends ReactMarkdownProps {
  children: string;
  className?: string;
  escapeHtml?: boolean;
  skipHtml?: boolean;
  renderPlainText?: boolean;
}

const TextRenderer = (as: any = "p") => ({
  children,
}: {
  children: ReactNode;
}) => <Text as={as}>{children}</Text>;

export const Markdown = ({
  children,
  className,
  escapeHtml = true,
  skipHtml = false,
  renderPlainText = false,
  ...rest
}: MarkdownProps) => {
  const renderers = renderPlainText
    ? {
        heading: TextRenderer(),
        strong: TextRenderer("span"),
        emphasis: TextRenderer("span"),
      }
    : undefined;

  return (
    <ReactMarkdown
      className={classNames(bem(cn), className)}
      source={children}
      escapeHtml={escapeHtml}
      skipHtml={skipHtml}
      renderers={renderers}
      {...rest}
    />
  );
};
