import styles from './Input.module.css'
import { forwardRef, type InputHTMLAttributes, type ReactNode } from 'react'
import { X } from 'lucide-react'

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  icon?: ReactNode
  onClear?: () => void
}

export const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ icon, onClear, className, value, ...rest }, ref) => {
    const showClear = onClear && value !== undefined && value !== ''
    return (
      <div className={`${styles.wrap} ${className ?? ''}`}>
        {icon && <span className={styles.icon}>{icon}</span>}
        <input
          ref={ref}
          className={`${styles.input} ${icon ? styles.hasIcon : ''} ${showClear ? styles.hasClear : ''}`}
          value={value}
          {...rest}
        />
        {showClear && (
          <button
            type="button"
            className={styles.clearBtn}
            onClick={onClear}
            aria-label="Clear search"
          >
            <X size={12} />
          </button>
        )}
      </div>
    )
  },
)

Input.displayName = 'Input'
