import { defineComponent, h, mergeProps } from 'vue'
import { Input, Textarea, AutoComplete } from '@arco-design/web-vue'

function shouldTrim(props, noTrim) {
  if (noTrim) return false
  if (props.type === 'password') return false
  return true
}

export function withInputTrim(Original) {
  return defineComponent({
    name: `Trim${Original.name || 'Input'}`,
    inheritAttrs: false,
    props: {
      ...(Original.props || {}),
      noTrim: {
        type: Boolean,
        default: false,
      },
    },
    // 仅声明包装层自行处理的事件；其余（如 AutoComplete 的 search）留在 attrs 中透传
    emits: ['update:modelValue', 'blur'],
    setup(props, { attrs, slots, emit }) {
      return () => {
        const { noTrim, modelValue, ...rest } = props

        const onUpdateModelValue = (value) => {
          emit('update:modelValue', value)
        }

        const onBlur = (ev) => {
          if (shouldTrim(props, noTrim) && typeof modelValue === 'string') {
            const trimmed = modelValue.trim()
            if (trimmed !== modelValue) {
              emit('update:modelValue', trimmed)
            }
          }
          emit('blur', ev)
          const attrBlur = attrs.onBlur
          if (attrBlur) {
            const handlers = Array.isArray(attrBlur) ? attrBlur : [attrBlur]
            handlers.forEach((fn) => typeof fn === 'function' && fn(ev))
          }
        }

        return h(
          Original,
          mergeProps(attrs, rest, {
            modelValue,
            'onUpdate:modelValue': onUpdateModelValue,
            onBlur,
          }),
          slots
        )
      }
    },
  })
}

const TRIM_COMPONENTS = [
  ['AInput', Input],
  ['AInputSearch', Input.Search],
  ['ATextarea', Textarea],
  ['AAutoComplete', AutoComplete],
]

export default {
  install(app) {
    TRIM_COMPONENTS.forEach(([name, component]) => {
      if (component) {
        app.component(name, withInputTrim(component))
      }
    })
  },
}
