"use client";

import {
	useRef,
	MutableRefObject,
	useLayoutEffect,
	ChangeEventHandler,
	useState,
} from "react";
import { StateHook } from "@/util";

// Autosize the text area
function textAreaAutoSize(
	textbox: MutableRefObject<HTMLTextAreaElement>
): void {
	if (!textbox.current || !textbox.current.style) return;
	textbox.current.style.height = "fit-content";
	textbox.current.style.height = `${textbox.current.scrollHeight}px`;
}

type EntityEditorTextAreaProps = {
	contentHook: StateHook<string>;
	className: string;
};

export function EntityEditorTextArea({
	contentHook,
	className,
}: EntityEditorTextAreaProps) {
	let textbox: any = useRef(undefined);

	useLayoutEffect(() => textAreaAutoSize(textbox));

	// Handle user input on the text area by updating state and autosizing the textfield
	const onTextAreaChange: ChangeEventHandler<HTMLTextAreaElement> = (e) => {
		contentHook?.setState(e.target.value); // Update State
		textAreaAutoSize(textbox); // Autosize the text area
	};

	return (
		<textarea
			key="input-content"
			onChange={onTextAreaChange}
			ref={textbox}
			value={contentHook?.state}
			style={{ height: "100%" }}
			className={className}
		/>
	);
}
