"use client";

import { useEffect, useRef } from "react";
import clsx from "clsx";

import styles from "./TextareaAutoResize.module.scss";

interface TextareaAutoResizeProps
  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  maxRows?: number;
}

export default function TextareaAutoResize({
  className,
  maxRows = 5,
  ...props
}: TextareaAutoResizeProps) {
  const ref = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    const textarea = ref.current;
    if (!textarea) return;
    textarea.style.height = "auto";
    const lineHeight = parseInt(
      getComputedStyle(textarea).lineHeight || "20",
      10
    );
    const maxHeight = lineHeight * maxRows + 24;
    textarea.style.height = Math.min(textarea.scrollHeight, maxHeight) + "px";
    textarea.style.overflowY =
      textarea.scrollHeight > maxHeight ? "auto" : "hidden";
    textarea.scrollTop = textarea.scrollHeight;
  }, [props.value, maxRows]);

  return (
    <textarea
      ref={ref}
      className={clsx(styles.textarea, className)}
      rows={1}
      {...props}
    />
  );
}
