import { onMounted, onUnmounted } from 'vue'
import { useEditorStore, useHistoryStore, useTemplateStore } from '@/stores'

/**
 * 键盘快捷键组合式函数
 * 
 * 支持的快捷键:
 * - Ctrl+Z: 撤销
 * - Ctrl+Y / Ctrl+Shift+Z: 重做
 * - Delete / Backspace: 删除选中线条
 * - 方向键: 微调 1px
 * - Shift+方向键: 微调 10px
 * - Ctrl+左右箭头: 上一个/下一个文件（批量模式）
 * - Ctrl+T: 应用选中的模板
 */
export function useKeyboardShortcuts() {
  const editorStore = useEditorStore()
  const historyStore = useHistoryStore()
  const templateStore = useTemplateStore()
  
  // 外部注入的回调函数
  let onLoadFileCallback: ((pair: { imagePath: string; jsonPath: string }) => void) | null = null
  let onApplyTemplateCallback: (() => void) | null = null
  
  function loadCurrentPair() {
    const pair = templateStore.currentFilePair
    if (pair && onLoadFileCallback) {
      onLoadFileCallback({
        imagePath: pair.image_path,
        jsonPath: pair.json_path
      })
    }
  }

  function handleKeyDown(e: KeyboardEvent) {
    // 如果焦点在输入框中，不处理快捷键
    const target = e.target as HTMLElement
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
      return
    }

    const isCtrl = e.ctrlKey || e.metaKey
    const isShift = e.shiftKey

    // Ctrl+Z: 撤销
    if (isCtrl && e.key === 'z' && !isShift) {
      e.preventDefault()
      performUndo()
      return
    }

    // Ctrl+Y 或 Ctrl+Shift+Z: 重做
    if ((isCtrl && e.key === 'y') || (isCtrl && e.key === 'z' && isShift)) {
      e.preventDefault()
      performRedo()
      return
    }
    
    // Ctrl+左箭头: 上一个文件
    if (isCtrl && e.key === 'ArrowLeft' && !isShift) {
      if (templateStore.hasFilePairs && templateStore.hasPrevPair) {
        e.preventDefault()
        templateStore.prevPair()
        loadCurrentPair()
      }
      return
    }
    
    // Ctrl+右箭头: 下一个文件
    if (isCtrl && e.key === 'ArrowRight' && !isShift) {
      if (templateStore.hasFilePairs && templateStore.hasNextPair) {
        e.preventDefault()
        templateStore.nextPair()
        loadCurrentPair()
      }
      return
    }
    
    // Ctrl+T: 应用选中的模板
    if (isCtrl && e.key === 't') {
      e.preventDefault()
      if (onApplyTemplateCallback && templateStore.selectedTemplateName && editorStore.hasData) {
        onApplyTemplateCallback()
      }
      return
    }

    // Delete / Backspace: 删除选中线条
    if (e.key === 'Delete' || e.key === 'Backspace') {
      if (editorStore.selectedLine) {
        e.preventDefault()
        editorStore.deleteSelectedLine()
      }
      return
    }

    // 方向键: 微调选中线条
    if (editorStore.selectedLine) {
      const step = isShift ? 10 : 1
      const { type } = editorStore.selectedLine

      switch (e.key) {
        case 'ArrowUp':
          if (type === 'h') {
            e.preventDefault()
            editorStore.nudgeSelectedLine(-step)
          }
          break
        case 'ArrowDown':
          if (type === 'h') {
            e.preventDefault()
            editorStore.nudgeSelectedLine(step)
          }
          break
        case 'ArrowLeft':
          if (type === 'v') {
            e.preventDefault()
            editorStore.nudgeSelectedLine(-step)
          }
          break
        case 'ArrowRight':
          if (type === 'v') {
            e.preventDefault()
            editorStore.nudgeSelectedLine(step)
          }
          break
      }
    }
  }

  function performUndo() {
    if (!historyStore.canUndo) return
    
    // 保存当前状态到重做栈
    const currentStructure = JSON.parse(JSON.stringify(editorStore.structure))
    historyStore.saveCurrentForRedo(currentStructure)
    
    // 恢复上一个状态
    const previousState = historyStore.undo()
    if (previousState) {
      editorStore.applyStructure(previousState)
    }
  }

  function performRedo() {
    if (!historyStore.canRedo) return
    
    // 保存当前状态到撤销栈
    const currentStructure = JSON.parse(JSON.stringify(editorStore.structure))
    historyStore.saveCurrentForUndo(currentStructure)
    
    // 恢复重做状态
    const nextState = historyStore.redo()
    if (nextState) {
      editorStore.applyStructure(nextState)
    }
  }

  onMounted(() => {
    window.addEventListener('keydown', handleKeyDown)
  })

  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown)
  })

  function setup() {
    window.addEventListener('keydown', handleKeyDown)
  }

  function cleanup() {
    window.removeEventListener('keydown', handleKeyDown)
  }
  
  // 注册回调函数
  function registerCallbacks(callbacks: {
    onLoadFile?: (pair: { imagePath: string; jsonPath: string }) => void
    onApplyTemplate?: () => void
  }) {
    if (callbacks.onLoadFile) {
      onLoadFileCallback = callbacks.onLoadFile
    }
    if (callbacks.onApplyTemplate) {
      onApplyTemplateCallback = callbacks.onApplyTemplate
    }
  }

  return {
    performUndo,
    performRedo,
    setup,
    cleanup,
    registerCallbacks,
    loadCurrentPair
  }
}
