import React, { useCallback, useEffect, useRef } from 'react'
import { useTabStore } from '../../stores/tabStore'

interface SourceEditorProps {
  darkMode: boolean
}

/**
 * 源码编辑模式 — 使用原生 textarea 编辑原始 Markdown 文本。
 * 内容实时同步到 tabStore，与 WYSIWYG 编辑器共享同一数据源。
 *
 * A2: 完全受控 — 所有变更通过 updateTabContent 驱动，
 * 手动写入 DOM 的反模式已移除；光标位置通过 ref + useEffect 恢复。
 */
export const SourceEditor = React.memo(function SourceEditor({ darkMode }: SourceEditorProps) {
  const activeTab = useTabStore(s => s.getActiveTab())
  const activeTabId = useTabStore(s => s.activeTabId)
  const updateTabContent = useTabStore(s => s.updateTabContent)
  const setModified = useTabStore(s => s.setModified)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  // A2: 记录格式化按键后的期望光标位置，在 content 变化后恢复
  const pendingSelectionRef = useRef<number | null>(null)

  useEffect(() => {
    if (pendingSelectionRef.current === null) return
    const textarea = textareaRef.current
    if (!textarea) return
    const pos = pendingSelectionRef.current
    // microtask：在 React 完成 DOM 更新后恢复光标
    requestAnimationFrame(() => {
      textarea.selectionStart = pos
      textarea.selectionEnd = pos
    })
    pendingSelectionRef.current = null
  }, [activeTab?.content])

  const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    if (!activeTabId) return
    updateTabContent(activeTabId, e.target.value)
    setModified(activeTabId, true)
  }, [activeTabId, updateTabContent, setModified])

  const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    const isCtrl = e.ctrlKey || e.metaKey
    const textarea = textareaRef.current
    if (!textarea || !activeTabId) return

    // Tab 插入两个空格而非跳转焦点
    if (e.key === 'Tab') {
      e.preventDefault()
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      const value = textarea.value
      const newValue = value.substring(0, start) + '  ' + value.substring(end)
      const newPos = start + 2
      updateTabContent(activeTabId, newValue)
      setModified(activeTabId, true)
      pendingSelectionRef.current = newPos
      return
    }

    // Ctrl+B: 粗体
    if (isCtrl && e.key === 'b') {
      e.preventDefault()
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      const value = textarea.value
      const selected = value.substring(start, end)
      const newValue = value.substring(0, start) + '**' + selected + '**' + value.substring(end)
      updateTabContent(activeTabId, newValue)
      setModified(activeTabId, true)
      pendingSelectionRef.current = selected ? start + 2 + selected.length + 2 : start + 2
      return
    }

    // Ctrl+I: 斜体
    if (isCtrl && e.key === 'i') {
      e.preventDefault()
      const start = textarea.selectionStart
      const end = textarea.selectionEnd
      const value = textarea.value
      const selected = value.substring(start, end)
      const newValue = value.substring(0, start) + '*' + selected + '*' + value.substring(end)
      updateTabContent(activeTabId, newValue)
      setModified(activeTabId, true)
      pendingSelectionRef.current = selected ? start + 1 + selected.length + 1 : start + 1
      return
    }
  }, [activeTabId, updateTabContent, setModified])

  return (
    <div className={`source-editor-wrapper${darkMode ? ' source-editor-dark' : ''}`}>
      <textarea
        ref={textareaRef}
        className="source-editor-textarea"
        value={activeTab?.content ?? ''}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        spellCheck={false}
        wrap="off"
        aria-label="Markdown 源码编辑器"
        placeholder="在此输入 Markdown 内容..."
      />
    </div>
  )
})

SourceEditor.displayName = 'SourceEditor'
