import { TextareaHTMLAttributes, forwardRef } from 'react';
import { getFormInputClasses, defaultLayoutConfig, type LayoutConfig } from '~/lib/layout-utils';

interface TextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'className'> {
  className?: string;
  config?: Partial<LayoutConfig>;
  label?: string;
  error?: string;
  helperText?: string;
  fullWidth?: boolean;
  resize?: 'none' | 'vertical' | 'horizontal' | 'both';
}

export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(({ 
  className = '', 
  config = {},
  label,
  error,
  helperText,
  fullWidth = true,
  resize = 'vertical',
  id,
  ...props
}, ref) => {
  const layoutConfig = { ...defaultLayoutConfig, ...config };
  const inputClasses = getFormInputClasses(!!error);
  
  const fullWidthClass = fullWidth ? 'w-full' : '';
  const resizeClass = {
    none: 'resize-none',
    vertical: 'resize-y',
    horizontal: 'resize-x',
    both: 'resize',
  }[resize];
  
  const inputId = id || `textarea-${Math.random().toString(36).substr(2, 9)}`;
  
  return (
    <div className={`${fullWidthClass} ${className}`} dir={layoutConfig.direction}>
      {label && (
        <label 
          htmlFor={inputId}
          className={`block text-sm font-medium mb-2 ${error ? 'text-red-700' : 'text-gray-700'} ${layoutConfig.direction === 'rtl' ? 'text-right' : 'text-left'}`}
        >
          {label}
        </label>
      )}
      
      <textarea
        ref={ref}
        id={inputId}
        className={`${inputClasses} ${resizeClass} min-h-[80px]`}
        dir={layoutConfig.direction}
        {...props}
      />
      
      {error && (
        <p className={`mt-2 text-sm text-red-600 ${layoutConfig.direction === 'rtl' ? 'text-right' : 'text-left'}`}>
          {error}
        </p>
      )}
      
      {helperText && !error && (
        <p className={`mt-2 text-sm text-gray-500 ${layoutConfig.direction === 'rtl' ? 'text-right' : 'text-left'}`}>
          {helperText}
        </p>
      )}
    </div>
  );
});

Textarea.displayName = 'Textarea';