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[]>,
) {
  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
    }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {
      e.preventDefault()
      handlers.copySelection()
      return
    }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'x') {
      e.preventDefault()
      handlers.cutSelection()
      return
    }
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') {
      e.preventDefault()
      handlers.pasteClipboard()
    }
  }

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