import React, { useRef, useEffect, ChangeEvent } from 'react';

interface Props {
  value: string;
  className?: string;
  placeholder?: string;
  disabled?: boolean;
  onChange: (value: string) => void;
  onBlur?: () => void;
}

const AutoExpandingTextArea: React.FC<Props> = ({
  value,
  className = 'w-full cursor-text px-7 py-8 input border-2 border-mti-gray-platinum bg-white rounded-3xl',
  placeholder = "Enter text here...",
  disabled = false,
  onChange,
  onBlur,
}) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const adjustHeight = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = `${textarea.scrollHeight}px`;
    }
  };

  useEffect(() => {
    adjustHeight();
    const timer = setTimeout(adjustHeight, 100);
    return () => clearTimeout(timer);
  }, [value]);

  const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    onChange(e.target.value);
    adjustHeight();
  };

  return (
    <textarea
      ref={textareaRef}
      value={value.replace(/\\n/g, '\n')}
      onChange={handleChange}
      className={className}
      placeholder={placeholder}
      style={{ overflow: 'hidden', resize: 'none' }}
      onBlur={onBlur}
      disabled={disabled}
      autoFocus
    />
  );
};

export default AutoExpandingTextArea;