import { ForwardedRef, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react";
import { MathText } from "./MathText";

export type DialogTextImperatives = {
	skip(): void;
}

export const DialogText = forwardRef((props: {children: string, speed?: number, onFinish?: () => void}, forwardedRef: ForwardedRef<DialogTextImperatives>) => {
	const {children: str, onFinish, speed = 15} = props;
	const [len, setLen] = useState(0);
	const interval = useRef<unknown>(null);

	useImperativeHandle(forwardedRef, () => {
		return {
			skip() {
				setLen(str.length);
			}
		}
	}, [str, setLen]);

	useLayoutEffect(() => {
		setLen(0);
	}, [str]);

	useEffect(() => {
		interval.current = setInterval(() => {
			setLen(l => {
				return Math.min(l+1, str.length)
			});
		}, 1000/speed);
		return () => {
			if (interval.current) {
				clearInterval(interval.current as any);
				interval.current = null;
			}
		};
	}, [str, setLen]);

	useLayoutEffect(() => {
		if (len === str.length) {
			if (interval.current) {
				clearInterval(interval.current as any);
				interval.current = null;
			}
			console.log("onFinish");
			onFinish && onFinish();
		}
	}, [len]);

	return <MathText>{str.slice(0, len)}</MathText>
});