import { ChangeEvent, ChangeEventHandler, ReactElement, useRef, useState } from "react"

type Props = {
    children:Array<ReactElement>
    onChange?:ChangeEventHandler<HTMLTextAreaElement>
}

export const AutoSizeTextArea = (props:Props) => {
    
    let textbox:any = useRef(undefined);

    const [content, setContent] = useState('');

    const adjustHeight = () => {
        if(!textbox.current || !textbox.current.style) return;
        textbox.current.style.height = "fit-content";
        textbox.current.style.height = `${textbox.current.scrollHeight}px`;
    }

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

    return <>
        <textarea ref={textbox} onChange={onChange} value={content}>{props.children}</textarea>
    </>
}