import * as React from 'react'

// --- Custom Hook for Input Clear Logic ---
export const useInputClear = ({
  value,
  defaultValue,
  onChange,
  type,
}: {
  value?: string | number | readonly string[]
  defaultValue?: string | number | readonly string[]
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
  isLoading?: boolean
  isValid?: boolean
  isInvalid?: boolean
  type?: string
}) => {
  const [internalValue, setInternalValue] = React.useState(
    defaultValue ? String(defaultValue) : '',
  )
  const [showPassword, setShowPassword] = React.useState(false)
  const inputRef = React.useRef<HTMLInputElement>(null)

  // Sync internal value when controlled value changes
  React.useEffect(() => {
    if (value !== undefined) {
      setInternalValue(String(value))
    }
  }, [value])

  const isControlled = value !== undefined
  const currentValue = isControlled ? String(value) : internalValue
  const hasValue = !!currentValue
  const isPassword = type === 'password'

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (isControlled) {
      // Controlled: just call onChange
      onChange?.(e)
    } else {
      // Uncontrolled: update internal state and call onChange
      setInternalValue(e.target.value)
      onChange?.(e)
    }
  }

  const handleClear = () => {
    if (isControlled) {
      // Controlled: trigger onChange with empty value
      onChange?.({
        target: { value: '' },
      } as React.ChangeEvent<HTMLInputElement>)
    } else {
      // Uncontrolled: clear internal state and DOM
      setInternalValue('')
      if (inputRef.current) {
        inputRef.current.value = ''
      }
      onChange?.({
        target: { value: '' },
      } as React.ChangeEvent<HTMLInputElement>)
    }

    // Keep focus on the input after clearing
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }

  const handleTogglePassword = () => {
    const newShowPassword = !showPassword

    setShowPassword(newShowPassword)

    // Force the input type change
    if (inputRef.current) {
      const newType = newShowPassword ? 'text' : 'password'
      inputRef.current.type = newType
      // Force a re-render to ensure the change is applied
      inputRef.current.dispatchEvent(new Event('input', { bubbles: true }))
    }
  }

  const canShowPasswordToggle = isPassword && hasValue

  return {
    hasValue,
    canShowPasswordToggle,
    showPassword,
    handleChange,
    handleClear,
    handleTogglePassword,
    inputRef,
  }
}
