import React from "react"
import remarkGfm from "remark-gfm"
import rehypeHighlight from 'rehype-highlight'
import ReactMarkdown from "react-markdown"

export interface IProps {
  children: string
}

export const Markdown: React.FC<IProps> = (props) => {
  const {children} = props
  return (
    <ReactMarkdown remarkPlugins={[
      remarkGfm,
    ]} rehypePlugins={[
      () => rehypeHighlight({ignoreMissing: true}),
    ]} components={{
      img: ({src, ...props}) => {
        if (src?.endsWith('.mp4')) {
          return (
            <video width={'100%'} controls>
              <source src={src} type="video/mp4" />
              Your browser does not support the video tag.
            </video>
          )
        }
        return <img src={src} {...props} />
      },
      h1: ({children, ...props}) => <h1 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h1>,
      h2: ({children, ...props}) => <h2 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h2>,
      h3: ({children, ...props}) => <h3 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h3>,
      h4: ({children, ...props}) => <h4 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h4>,
      h5: ({children, ...props}) => <h5 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h5>,
      h6: ({children, ...props}) => <h6 id={typeof children[0] === 'string' ? children[0].replaceAll(' ', '-') : undefined} {...props}>{children}</h6>,
    }}>{children.replaceAll('<center>', '').replaceAll('</center>', '')}</ReactMarkdown>
  )
}
