import { onMounted, onBeforeUnmount, type Ref } from 'vue'
import type { FileEntry } from '@/types/api'

export interface FilesHotkeyHandlers {
  refresh: () => void
  goUp: () => void
  renameSelection: () => void
  deleteSelection: () => void
  selectAll: () => void
  copySelection: () => void
  cutSelection: () => void
  pasteClipboard: () => void
}

function isTypingTarget(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false
  const tag = target.tagName
  return tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable
}

export function useFilesHotkeys(
  handlers: FilesHotkeyHandlers,
  selectedFiles: Ref<FileEntry[]>,
  canPaste: Ref<boolean>,
) {
  function onKeydown(e: KeyboardEvent) {
    if (isTypingTarget(e.target)) return

    if (e.key === 'F5') {
      e.preventDefault()
      handlers.refresh()
      return
    }
    if (e.key === 'Backspace') {
      e.preventDefault()
      handlers.goUp()
      return
    }
    if (e.key === 'F2' && selectedFiles.value.length === 1) {
      e.preventDefault()
      handlers.renameSelection()
      return
    }
    if (e.key === 'Delete' && selectedFiles.value.length > 0) {
      e.preventDefault()
      handlers.deleteSelection()
    }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'a') {
      e.preventDefault()
      handlers.selectAll()
      return
    }
    // Ctrl+C / Ctrl+X：仅在有勾选文件时生效，否则让浏览器处理原生复制
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {
      if (selectedFiles.value.length > 0) {
        e.preventDefault()
        handlers.copySelection()
      }
      return
    }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'x') {
      if (selectedFiles.value.length > 0) {
        e.preventDefault()
        handlers.cutSelection()
      }
      return
    }
    // Ctrl+V：仅在剪贴板有内容时生效
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') {
      if (canPaste.value) {
        e.preventDefault()
        handlers.pasteClipboard()
      }
    }
  }

  onMounted(() => window.addEventListener('keydown', onKeydown))
  onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
}
