// hooks/useEnterKeyTrigger.js
import { onMounted, onUnmounted, unref } from 'vue'

interface UseEnterKeyTriggerOptions {
  formRef: Ref<HTMLElement | null> | HTMLElement | VueComponent
  btnRef: Ref<HTMLElement | null> | HTMLElement | VueComponent
  callback?: (event: KeyboardEvent) => void
}
interface VueComponent {
  $el: HTMLElement
}
export function useEnterKeyTrigger(options: UseEnterKeyTriggerOptions) {
  const { formRef, btnRef, callback } = options

  if (!formRef) {
    console.warn('useEnterKeyTrigger: formRef is required')
    return
  }

  const handleKeydown = (event: KeyboardEvent) => {
    if (event.key !== 'Enter') return
    // 阻止默认行为
    event.preventDefault()
    event.stopPropagation()

    // 执行回调或点击按钮
    if (typeof callback === 'function') {
      callback(event)
    } else {
      const btnElement = unref(btnRef) as VueComponent
      if (btnElement) {
        const element = btnElement.$el || btnElement
        element.click()
      }
    }
  }

  onMounted(() => {
    const formElement = unref(formRef) as VueComponent
    if (formElement) {
      const element = formElement.$el || formElement
      element.addEventListener('keydown', handleKeydown, true) // 使用捕获阶段
    }
  })

  onUnmounted(() => {
    const formElement = unref(formRef) as VueComponent
    if (formElement) {
      const element = formElement.$el || formElement
      element.removeEventListener('keydown', handleKeydown, true)
    }
  })
}
