import Prism, { highlight } from 'prismjs'
import { type PropsWithChildren } from 'react'

import { RichText } from '@/lib/notion/types'
import richTextAsPlainText from '@/lib/notion/utils/richTextToPlainText'

export interface Props {
  language: string
  codeRichText: RichText
}

/**
 * This is only used for the RSS feed
 */
export function SyncCodeSnippet({
  language,
  codeRichText,
}: PropsWithChildren<Props>) {
  const highlightedCodeHtml = highlight(
    richTextAsPlainText(codeRichText),
    Prism.languages[language],
    language,
  )

  return (
    <pre className="rounded border border-neutral-500 bg-neutral-800 p-4">
      <code
        className={`language-${language}`}
        dangerouslySetInnerHTML={{ __html: highlightedCodeHtml }}
      />
    </pre>
  )
}

export default async function CodeSnippet(props: PropsWithChildren<Props>) {
  await import(`prismjs/components/prism-${props.language}.min.js`)
  // @ts-expect-error CSS not JS
  await import('prismjs/themes/prism-tomorrow.min.css')
  // @ts-expect-error CSS not JS
  await import('prismjs/themes/prism.min.css')

  return <SyncCodeSnippet {...props} />
}
