import { useLayoutEffect, useRef } from "react";
import type { TextareaHTMLAttributes } from "react";

type PromptTextareaProps = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "rows"> & {
  maxHeight?: number;
};

export function PromptTextarea({ className, maxHeight = 240, onInput, ...props }: PromptTextareaProps) {
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);

  function syncHeight() {
    const textarea = textareaRef.current;
    if (!textarea) {
      return;
    }

    textarea.style.height = "0px";
    const nextHeight = Math.min(textarea.scrollHeight, maxHeight);
    textarea.style.height = `${nextHeight}px`;
    textarea.style.overflowY = textarea.scrollHeight > maxHeight ? "auto" : "hidden";
  }

  useLayoutEffect(() => {
    syncHeight();
  }, [maxHeight, props.value]);

  return (
    <textarea
      {...props}
      ref={textareaRef}
      rows={1}
      className={className ? `prompt-textarea ${className}` : "prompt-textarea"}
      onInput={(event) => {
        syncHeight();
        onInput?.(event);
      }}
    />
  );
}
