// Form Textarea Component
import { TextareaHTMLAttributes, forwardRef } from 'react';
import { clsx } from 'clsx';
import './FormTextarea.css';

interface FormTextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
  label?: string;
  error?: string;
  helperText?: string;
  showCharCount?: boolean;
  maxLength?: number;
}

const FormTextarea = forwardRef<HTMLTextAreaElement, FormTextareaProps>(
  ({ label, error, helperText, showCharCount, maxLength, className, value, onChange, ...props }, ref) => {
    const charCount = typeof value === 'string' ? value.length : 0;

    return (
      <div className="form-textarea">
        {label && (
          <label className="form-textarea__label" htmlFor={props.id}>
            {label}
            {props.required && <span className="form-textarea__required">*</span>}
          </label>
        )}
        <textarea
          ref={ref}
          className={clsx('form-textarea__textarea', { 'form-textarea__textarea--error': error }, className)}
          value={value}
          onChange={onChange}
          maxLength={maxLength}
          {...props}
        />
        <div className="form-textarea__footer">
          {error && <span className="form-textarea__error">{error}</span>}
          {helperText && !error && <span className="form-textarea__helper">{helperText}</span>}
          {showCharCount && maxLength && (
            <span className="form-textarea__char-count">
              {charCount} / {maxLength}
            </span>
          )}
        </div>
      </div>
    );
  }
);

FormTextarea.displayName = 'FormTextarea';

export default FormTextarea;

