import * as React from 'react'

import { cn } from '@/lib/utils'

type InputSize = 'small' | 'large'

interface InputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'> {
  prefixIcon?: React.ReactNode
  showCount?: boolean
  size?: InputSize
  error?: boolean
}

function Input({
  className,
  type,
  prefixIcon,
  showCount = false,
  error = false,
  maxLength,
  value,
  size = 'large',
  ...props
}: InputProps) {
  let inputValue = ''
  if (typeof value === 'string' || typeof value === 'number') {
    inputValue = String(value)
  }
  const count = inputValue.length

  return (
    <div
      className={cn(
        'relative flex w-full items-center',
        error && '[&>input]:border-primary-variant-press'
      )}
    >
      {prefixIcon && (
        <span className="pointer-events-none absolute left-3 flex items-center">{prefixIcon}</span>
      )}
      <input
        type={type}
        data-slot="input"
        className={cn(
          'placeholder:text-txt-tertiary-normal bg-surface-element-normal rounded-sm',
          'selection:bg-surface-element-normal selection:text-txt-primary-normal',
          'border border-solid border-transparent',
          'hover:border-outline-hover focus-visible:border-primary-variant-press',
          'transition-[color,box-shadow] outline-none',
          'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
          size === 'small' && 'txt-body-m flex h-8 w-full min-w-0 px-4 py-1',
          size === 'large' && 'txt-body-l flex h-12 w-full min-w-0 px-4 py-1',
          error && '!border-important-variant-normal',
          prefixIcon && 'pl-10',
          showCount && 'pr-[52px]',
          className
        )}
        maxLength={maxLength}
        value={value}
        aria-invalid={error}
        {...props}
      />
      {showCount && typeof maxLength === 'number' && (
        <span className="text-txt-secondary-normal absolute right-3 text-xs select-none">
          {count}/{maxLength}
        </span>
      )}
    </div>
  )
}

export { Input }
