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

function useResettableAnimation(animation: string, duration: number): [string, number] {
    const i = useRef(0);
    const j = useRef(0);
    const [stateAnimation, setStateAnimation] = useState(animation);
    const [stateAnimationReset, setStateAnimationReset] = useState<typeof animation>(undefined);
    const [stateDuration, setStateDuration] = useState(duration);
    const [stateDurationReset, setStateDurationReset] = useState<typeof duration>(undefined);

    // Reset animation, save it temporary so when changing it, it needs to be to "none" and then the needed one
    useEffect(() => {
        // Avoid first rendering as the first is animated at mount-time
        if (i.current > 0) {
            if (animation === "none") {
                setStateAnimation(animation);
            } else {
                setStateAnimation("none");
                setStateAnimationReset(animation);
            }
        }
        i.current++;
    }, [animation]);

    useEffect(() => {
        // Avoid first rendering as the first is animated at mount-time
        if (j.current > 0) {
            if (duration === 0) {
                setStateDuration(duration);
            } else {
                setStateDuration(0);
                setStateDurationReset(duration);
                setStateAnimation("none");
                setStateAnimationReset(animation);
            }
        }
        j.current++;
    }, [duration]);

    useEffect(() => {
        if (stateAnimationReset !== undefined) {
            setStateAnimation(stateAnimationReset);
            setStateAnimationReset(undefined);
        }
    }, [stateAnimationReset]);

    useEffect(() => {
        if (stateDurationReset !== undefined) {
            setStateDuration(stateDurationReset);
            setStateDurationReset(undefined);
        }
    }, [stateDurationReset]);

    return [stateAnimation, stateDuration];
}

export { useResettableAnimation };
