import { memo, useMemo, useState, useCallback, type MouseEvent } from "react"
import { Button, Modal, Space } from "antd"
import { sanitizeRichText } from "../utils/richText"
import { injectLazyImageMarkers } from "./LazyImage"

interface RichTextContentProps {
  value?: string | null
  /** Use admin API for thumbnail URLs (default false) */
  admin?: boolean
}

/**
 * RichTextContent — renders sanitized rich text with:
 * - React.memo to skip re-renders when value hasn't changed
 * - Thumbnail-based inline images for performance
 * - Server-compatible lazy-loading markers on images
 * - Event delegation for image click → preview (full-res)
 * - DOMPurify sanitization memoized on value
 */
const RichTextContent = memo(function RichTextContent({ value, admin = false }: RichTextContentProps) {
  const [preview, setPreview] = useState<{ src: string; alt: string } | null>(null)

  // Memoize the sanitized + thumbnail-injected HTML
  const html = useMemo(() => {
    const clean = sanitizeRichText(value)
    return injectLazyImageMarkers(clean, admin)
  }, [value, admin])

  const handleClick = useCallback((event: MouseEvent<HTMLDivElement>) => {
    const target = event.target
    if (!(target instanceof HTMLElement)) return
    const image = target.closest("img")
    if (!image) return
    event.preventDefault()
    // Use the full-resolution original URL for preview, not the thumbnail
    const src = image.getAttribute("data-original-src") || image.getAttribute("src")
    if (!src) return
    setPreview({
      src,
      alt: image.getAttribute("alt") || image.getAttribute("title") || "图片预览",
    })
  }, [])

  const closePreview = useCallback(() => setPreview(null), [])

  return (
    <>
      <div
        className="qycw-rich-text-content"
        onClick={handleClick}
        dangerouslySetInnerHTML={{ __html: html }}
      />
      <Modal
        open={!!preview}
        title={preview?.alt}
        footer={preview ? (
          <Space>
            <Button href={preview.src} target="_blank" rel="noreferrer">
              打开原图
            </Button>
            <Button type="primary" href={preview.src} download>
              下载图片
            </Button>
          </Space>
        ) : null}
        centered
        width={960}
        style={{ maxWidth: "92vw" }}
        onCancel={closePreview}
        destroyOnHidden
      >
        {preview && (
          <img
            src={preview.src}
            alt={preview.alt}
            style={{
              display: "block",
              maxWidth: "100%",
              maxHeight: "78vh",
              margin: "0 auto",
              objectFit: "contain",
            }}
          />
        )}
      </Modal>
    </>
  )
})

export default RichTextContent
