import * as React from "react";
import { useRemark } from "react-remark";

import { Anchor } from "../Anchor/Anchor";
import { Header, Text, TextVariant } from "../Text/Text";

function getRehypeOptions(props: MarkdownProps) {
  const { textVariant = "text-md/normal" } = props;
  return {
    components: {
      h1: (props: any) => <Header tag="h1" variant="header-xl" {...props} />,
      h2: (props: any) => <Header tag="h2" variant="header-lg" {...props} />,
      h3: (props: any) => <Header tag="h3" variant="header-md" {...props} />,
      h4: (props: any) => <Header tag="h4" variant="header-sm" {...props} />,
      h5: (props: any) => <Header tag="h5" variant="header-xs" {...props} />,
      p: (props: any) => <Text {...props} variant={textVariant} />,
      a: (props: any) => <Anchor {...props} />,
    },
  };
}

export interface MarkdownProps {
  children: string;
  textVariant?: TextVariant;
}

export function Markdown(props: MarkdownProps) {
  const { children } = props;
  const [renderedContent, setContent] = useRemark({ rehypeReactOptions: getRehypeOptions(props) });

  React.useEffect(() => {
    setContent(children);
  }, [children, setContent]);

  return <>{renderedContent}</>;
}
