import * as React from 'react'

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

interface TextareaProps extends React.ComponentProps<'textarea'> {
  showCount?: boolean
  error?: boolean
}

function Textarea({
  className,
  showCount = false,
  error = false,
  maxLength,
  value,
  ...props
}: TextareaProps) {
  let inputValue = ''
  if (typeof value === 'string' || typeof value === 'number') {
    inputValue = String(value)
  }
  const count = inputValue.length

  return (
    <div className={cn('relative w-full', error && '[&>textarea]:border-primary-variant-press')}>
      <textarea
        data-slot="textarea"
        className={cn(
          'flex field-sizing-content min-h-[124px]',
          'placeholder:text-txt-tertiary-normal bg-surface-element-normal txt-body-l 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',
          'w-full min-w-0 px-4 py-3 transition-[color,box-shadow] outline-none',
          'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
          error && '!border-important-variant-normal',
          showCount && 'pb-8',
          className
        )}
        maxLength={maxLength}
        value={value}
        aria-invalid={error}
        {...props}
      />
      {showCount && typeof maxLength === 'number' && (
        <span className="text-txt-secondary-normal absolute right-4 bottom-3 text-xs select-none">
          {count}/{maxLength}
        </span>
      )}
    </div>
  )
}

export { Textarea }
