import DOMPurify from 'dompurify'
import { marked } from 'marked'
import { useDeferredValue, useMemo } from 'react'

import { cn } from '@/lib/utils'

type MarkdownPreviewProps = {
  markdown: string
  className?: string
}

marked.setOptions({
  breaks: true,
  gfm: true,
})

export function MarkdownPreview({ markdown, className }: MarkdownPreviewProps) {
  const deferredMarkdown = useDeferredValue(markdown)
  const html = useMemo(() => {
    const rendered = marked.parse(deferredMarkdown || '暂无内容。')
    return DOMPurify.sanitize(typeof rendered === 'string' ? rendered : '')
  }, [deferredMarkdown])

  return (
    <div className={cn('h-full overflow-y-auto bg-[#fcfcfd]', className)}>
      <article
        className={cn(
          'mx-auto max-w-4xl px-8 py-8 text-[15px] leading-8 text-slate-700',
          '[&_a]:text-blue-600 [&_a]:underline [&_blockquote]:border-l-4 [&_blockquote]:border-slate-300 [&_blockquote]:bg-slate-100/80 [&_blockquote]:px-4 [&_blockquote]:py-3 [&_blockquote]:italic',
          '[&_code]:rounded [&_code]:bg-slate-100 [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em]',
          '[&_h1]:mt-2 [&_h1]:text-3xl [&_h1]:font-semibold [&_h1]:tracking-tight [&_h2]:mt-8 [&_h2]:text-2xl [&_h2]:font-semibold',
          '[&_h3]:mt-6 [&_h3]:text-xl [&_h3]:font-semibold [&_hr]:my-8 [&_hr]:border-slate-200',
          '[&_li]:my-1 [&_ol]:my-4 [&_ol]:list-decimal [&_ol]:pl-6 [&_p]:my-4 [&_pre]:my-5 [&_pre]:overflow-x-auto [&_pre]:rounded-2xl [&_pre]:bg-slate-950 [&_pre]:p-4 [&_pre]:text-sm [&_pre]:text-slate-100 [&_pre_code]:bg-transparent [&_pre_code]:p-0',
          '[&_table]:my-6 [&_table]:w-full [&_table]:border-collapse [&_table]:overflow-hidden [&_table]:rounded-2xl [&_table]:border [&_table]:border-slate-200 [&_tbody_tr:nth-child(even)]:bg-slate-50/70 [&_td]:border [&_td]:border-slate-200 [&_td]:px-3 [&_td]:py-2 [&_th]:border [&_th]:border-slate-200 [&_th]:bg-slate-100 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left',
          '[&_ul]:my-4 [&_ul]:list-disc [&_ul]:pl-6',
        )}
        dangerouslySetInnerHTML={{ __html: html }}
      />
    </div>
  )
}
