import { onMounted, onUnmounted, type Ref } from 'vue'

export function useSearchKeyboardShortcuts(searchInputRef: Ref<any>) {
  const focusSearchInput = () => {
    if (searchInputRef.value?.$el) {
      // Access the underlying HTML input element from the Shadcn Input component
      const inputElement = searchInputRef.value.$el.querySelector('input') || searchInputRef.value.$el
      if (inputElement && typeof inputElement.focus === 'function') {
        inputElement.focus()
      }
    }
  }

  const blurSearchInput = () => {
    if (searchInputRef.value?.$el) {
      const inputElement = searchInputRef.value.$el.querySelector('input') || searchInputRef.value.$el
      if (inputElement && typeof inputElement.blur === 'function') {
        inputElement.blur()
      }
    }
  }

  const handleGlobalKeydown = (event: KeyboardEvent) => {
    // ⌘K or Ctrl+K to focus search
    if ((event.metaKey || event.ctrlKey) && event.key === 'k') {
      event.preventDefault()
      focusSearchInput()
    }
  }

  const handleSearchKeydown = (event: KeyboardEvent) => {
    // Escape key clears search or blurs input
    if (event.key === 'Escape') {
      event.preventDefault()
      return true // Signal to clear search
    }
    return false
  }

  onMounted(() => {
    document.addEventListener('keydown', handleGlobalKeydown)
  })

  onUnmounted(() => {
    document.removeEventListener('keydown', handleGlobalKeydown)
  })

  return {
    focusSearchInput,
    blurSearchInput,
    handleSearchKeydown
  }
}