import { useEffect, useRef } from "react";
import TextAreaProps from "./TextArea.interface";
import "./TextArea.scss";

const TextArea = ({ ...props }: TextAreaProps) => {
  const textAreaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    const resizeObserver = new ResizeObserver(() => {
      if (textAreaRef.current) {
        textAreaRef.current.style.height = "auto";
        textAreaRef.current.style.height = `${
          textAreaRef.current.scrollHeight + 2
        }px`;
      }
    });

    if (textAreaRef.current) {
      resizeObserver.observe(textAreaRef.current);
    }

    return () => {
      if (textAreaRef.current) {
        resizeObserver.unobserve(textAreaRef.current);
      }
    };
  }, [props.value]);

  return (
    <textarea
      {...props}
      ref={textAreaRef}
      className={`auto-expand-textarea ${props.className}`}
    />
  );
};

export default TextArea;
