import React, { useState, useEffect, useCallback, useRef } from 'react'
import { useTabStore } from '../../stores/tabStore'
import { useEditorStore } from '../../stores/editorStore'
import { renderMarkdown } from '../../lib/markdown'
import { LoadingSpinner } from '../LoadingSpinner/LoadingSpinner'

// PF-07: 防抖延迟常量
const PREVIEW_DEBOUNCE_MS = 150

export const Preview = React.memo(function Preview() {
  const [html, setHtml] = useState('')
  const [rendering, setRendering] = useState(false)
  const previewRef = useRef<HTMLDivElement>(null)
  const requestIdRef = useRef(0)
  const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const activeTab = useTabStore(s => s.getActiveTab())
  const activeTabId = useTabStore(s => s.activeTabId)
  const setLoading = useEditorStore(s => s.setLoading)

  // PF-07: 响应式渲染 + 防抖
  useEffect(() => {
    if (!activeTab) {
      setHtml('')
      setRendering(false)
      setLoading('markdown-render', false)
      return
    }

    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current)
    }

    setRendering(true)
    setLoading('markdown-render', true)

    debounceTimerRef.current = setTimeout(() => {
      const requestId = ++requestIdRef.current
      renderMarkdown(activeTab.content, activeTab.filePath).then((result: string) => {
        if (requestId === requestIdRef.current) {
          setHtml(result)
          setRendering(false)
          setLoading('markdown-render', false)
        }
      })
    }, PREVIEW_DEBOUNCE_MS)

    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- activeTab is a derived reference (from getActiveTab()), we track content/filePath via optional chaining
  }, [activeTabId, activeTab?.content, activeTab?.filePath, setLoading])

  // 拦截链接点击
  const handleClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    const link = (e.target as HTMLElement).closest('a')
    if (!link) return
    e.preventDefault()
    const href: string | null = link.getAttribute('href')
    if (!href) return
    if (href.startsWith('#')) {
      const target = previewRef.current?.querySelector(href)
      if (target) target.scrollIntoView({ behavior: 'smooth' })
      return
    }
    try {
      const url = new URL(href)
      if (url.protocol !== 'http:' && url.protocol !== 'https:') return
    } catch {
      return
    }
    if (window.electronAPI?.openExternal) {
      window.electronAPI.openExternal(href)
    } else {
      window.open(href, '_blank', 'noopener')
    }
  }, [])

  return (
    <div
      ref={previewRef}
      id="preview"
      className="markdown-body"
      role="region"
      aria-label="Markdown预览"
      aria-live="polite"
      aria-busy={rendering}
      onClick={handleClick}
    >
      {rendering && html === '' && (
        <div className="preview-loading" aria-label="正在渲染Markdown">
          <LoadingSpinner size="medium" label="正在渲染..." />
        </div>
      )}
      <div dangerouslySetInnerHTML={{ __html: html }} />
    </div>
  )
})

Preview.displayName = 'Preview'
