import { useCallback, useEffect, useState } from "react";
import { ReactComponent as OnTouchCogIcon } from "../assets/blocks/ontouchcog-bare.svg";
import { ReactComponent as TickIcon } from "../assets/green-tick.svg";
import styles from "./styles.module.css";
import { getConnectedCog } from "../utils/CogManager";
import Cog from "@robotical/webapp-types/dist-types/src/application/RAFTs/Cog/Cog";
import ClickCogAnimation from "./ClickCogAnimation";

type Props = {
    nextPhase: () => void;
};

export function Phase0({ nextPhase }: Props) {
    const [tickIconState, setTickIconState] = useState<"hidden" | "visible" | "animation">("hidden");
    const [cogIconState, setCogIconState] = useState<"hidden" | "visible" | "animation">("visible");

    const onCogButtonClick = useCallback(() => {
        setCogIconState("animation");
    }, []);

    useEffect(() => {
        const connectedCog = getConnectedCog();
        if (connectedCog) {
            const eventName = (connectedCog as Cog).publishedDataAnalyser.eventsMap.buttonClick.release;
            (connectedCog as Cog).publishedDataAnalyser.addListener(eventName, onCogButtonClick);

            return () => {
                (connectedCog as Cog).publishedDataAnalyser.removeListener(eventName, onCogButtonClick);
            };
        }
    }, []);

    const onCogIconAnimationEnd = useCallback(() => {
        setCogIconState("hidden");
        setTickIconState("animation");
    }, []);

    const onTickIconAnimationEnd = useCallback(() => {
        nextPhase();
    }, []);

    const cogIconClassNames = [
        styles.bareBlockIconFullScreen,
        cogIconState === "animation" ? styles.fadeOutAnimation : "",
        cogIconState === "hidden" ? styles.hide : "",
        cogIconState === "visible" ? styles.show : "",

    ].join(" ");

    const tickIconClassNames = [
        styles.tickIconFullScreen,
        tickIconState === "animation" ? styles.fadeInAnimation : "",
        tickIconState === "hidden" ? styles.hide : "",
        tickIconState === "visible" ? styles.show : "",
    ].join(" ");

    return (
        <div className={styles.singleColumnContainer}>
            <div onAnimationEnd={onCogIconAnimationEnd}>
                <ClickCogAnimation className={cogIconClassNames}/>
            </div>
            <TickIcon className={tickIconClassNames} onAnimationEnd={onTickIconAnimationEnd} />
        </div>
    );
}