import React from "react"
import ReactDOMServer from "react-dom/server"
import marked from "marked"
import cls from "classnames"
import hljs from "highlight.js"
import "highlight.js/styles/github.css"
import * as styles from "./index.module.scss"
import { addCatalogueNode } from "@/components/markdown-catalogue/catalogue"

interface IProps {
  body: string
  className?: string
  needAnchor?: boolean
}

const markdown: React.FC<IProps> = ({ body, className, needAnchor }) => {
  const highlight = (code: string, lang: string) => {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang, ignoreIllegals: true })
        .value
    } else {
      return hljs.highlightAuto(code).value
    }
  }

  const renderer = {
    image(href: string) {
      const match = href.toLowerCase().match(/^.*\.(mp)4$/)
      if (match)
        return ReactDOMServer.renderToString(
          <video
            crossOrigin="anonymous"
            loop
            controls
            preload="meta"
            width="100%"
            src={href}
          />
        )
      return false
    },
    heading(text: string, level: number) {
      if (level === 1) return ""
      if (level > 4) return false // ####
      if (level < 2) return false // ##
      if (needAnchor) {
        const { anchor } = addCatalogueNode(text, level, [], [])
        return `<h${level} id="${anchor}">${text}</h${level}>`
      } else {
        return false
      }
    },
    link(href: string, title: string, text: string) {
      return ` <a href="${href.replace(/\s|[\r\n]/g, "-")}">
          ${text}
        </a>`
    },
  }

  marked.use({ renderer, highlight })

  return (
    <div
      className={cls(className, styles.markdown)}
      dangerouslySetInnerHTML={{ __html: body && marked(body) }}
    ></div>
  )
}

export default markdown
