import { clsx } from 'clsx';
import { forwardRef } from 'react';

import { Merge } from '../utils';
import { inputClassNameBase } from './_common';
import { useTextareaCharacterCount, useInputAttributes } from './contexts';

export interface TextAreaProps extends Merge<
  React.ComponentPropsWithRef<'textarea'>,
  {
    'aria-invalid'?: boolean;
  }
> {}

export const TextArea = forwardRef(function TextArea(
  { className, maxLength, ...restProps }: TextAreaProps,
  reference: React.ForwardedRef<HTMLTextAreaElement | null>,
) {
  const inputAttributes = useInputAttributes();
  const value = restProps.value ?? restProps.defaultValue ?? '';
  const currentLength = typeof value === 'string' ? value.length : String(value).length;

  useTextareaCharacterCount(currentLength, maxLength);

  return (
    <textarea
      ref={reference}
      className={clsx(className, inputClassNameBase(), 'np-text-area')}
      maxLength={maxLength}
      {...inputAttributes}
      {...restProps}
    />
  );
});
