import React, { forwardRef } from 'react';

interface FormTextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  label?: string;
  error?: string;
  hint?: string;
  /** Full width */
  fullWidth?: boolean;
  /** Container class name */
  containerClassName?: string;
  /** Show character count */
  showCharCount?: boolean;
  /** Max characters for count display */
  maxChars?: number;
}

export const FormTextarea = forwardRef<HTMLTextAreaElement, FormTextareaProps>(
  (
    {
      label,
      error,
      hint,
      fullWidth = true,
      containerClassName = '',
      className = '',
      id,
      showCharCount = false,
      maxChars,
      value,
      ...props
    },
    ref
  ) => {
    const textareaId = id || props.name || `textarea-${Math.random().toString(36).substr(2, 9)}`;
    const charCount = typeof value === 'string' ? value.length : 0;

    const baseClasses =
      'px-3 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 transition-colors resize-y';

    const stateClasses = error
      ? 'border-red-500 dark:border-red-500 focus:ring-red-500 focus:border-red-500'
      : 'border-gray-300 dark:border-gray-600';

    const disabledClasses = props.disabled
      ? 'bg-gray-100 dark:bg-gray-800 cursor-not-allowed opacity-60'
      : '';

    const widthClass = fullWidth ? 'w-full' : '';

    return (
      <div className={`${containerClassName}`}>
        {label && (
          <label
            htmlFor={textareaId}
            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
          >
            {label}
            {props.required && <span className="text-red-500 ml-1">*</span>}
          </label>
        )}

        <textarea
          ref={ref}
          id={textareaId}
          value={value}
          className={`${baseClasses} ${stateClasses} ${disabledClasses} ${widthClass} ${className}`}
          {...props}
        />

        <div className="flex justify-between items-center mt-1">
          <div>
            {error && (
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            )}

            {hint && !error && (
              <p className="text-sm text-gray-500 dark:text-gray-400">{hint}</p>
            )}
          </div>

          {showCharCount && (
            <p className={`text-sm ${maxChars && charCount > maxChars ? 'text-red-500' : 'text-gray-500 dark:text-gray-400'}`}>
              {charCount}{maxChars ? `/${maxChars}` : ''}
            </p>
          )}
        </div>
      </div>
    );
  }
);

FormTextarea.displayName = 'FormTextarea';

export default FormTextarea;
