import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import './TextArea.scss';
import Label from '../Label';
import { LabelProps } from '../Label/Label';

export interface TextAreaProps
  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  variant?: 'default' | 'success' | 'danger' | 'controlled';
  capacity?: number;
  labelProps?: LabelProps;
  error?: string;
  requiredMessage?: string;
  value?: string;
  rows?: number;
  cols?: number;
  resize?: boolean;
}

const TextArea: React.FC<TextAreaProps> = ({
  variant = 'default',
  capacity = 0,
  labelProps,
  error = '',
  requiredMessage = 'Please enter comments',
  value = '',
  required = false,
  rows = 4,
  cols = 40,
  resize = false,
  ...props
}) => {
  let errorMessage = '';
  if (error) {
    errorMessage = error;
  } else {
    if (required) {
      errorMessage = requiredMessage;
    }
  }

  return (
    <div className="textarea-container">
      {labelProps && (
        <Label
          {...labelProps}
          label={labelProps.label || ''}
          required={required}
        />
      )}
      <textarea
        {...props}
        className={classNames(
          'textarea',
          `textarea--${variant}`,
          `textarea--controlled--${!!error ? 'error' : ''}`,
          { 'textarea--resize': !resize }
        )}
        value={value}
        rows={rows}
        cols={cols}
        maxLength={capacity || 9999}
      />
      <div className="error-msg-character-count">
        <span>
          {(required || error) && (
            <span className="error-msg">{errorMessage}</span>
          )}
        </span>
        {!!capacity && (
          <span>
            <span>{value?.length}</span>/{capacity}
          </span>
        )}
      </div>
    </div>
  );
};

export default TextArea;
