import { useCallback, useEffect, useRef, useState } from "react";
import { ReactComponent as TickIcon } from "../assets/green-tick.svg";
import styles from "./styles.module.css";
import { IRefPhaserGame, PhaserGame } from "../tutorial-game/PhaserGame";
import { EventBus } from "../tutorial-game/EventBus";
import { Sky } from "../tutorial-game/entities/Sky";
import { PosterItem } from "../types";

type Props = {
    nextPhase: () => void;
    BlocksConnectedIcon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
    initialBlock: PosterItem;
};

export function GenericPhase({ nextPhase, BlocksConnectedIcon, initialBlock }: Props) {
    const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "40vw", height: "30vh", visibility: "hidden" } as React.CSSProperties);

    const [tickIconState, setTickIconState] = useState<"hidden" | "visible" | "animation">("hidden");
    const [blocksIconState, setBlocksIconState] = useState<"hidden" | "visible" | "animation">("visible");
    const phaserGameRef = useRef<IRefPhaserGame>(null);

    const cogClickedCounter = useRef(0);
    const cogJumpedCounter = useRef(0);
    const delayedCompletionTimeoutRef = useRef<number | undefined>();

    const onCogButtonClick = useCallback(() => {
        cogClickedCounter.current++;
        if (cogClickedCounter.current === 3) {
            setBlocksIconState("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);
    //         };
    //     }
    // }, []);

    useEffect(() => {
        const handleSkyReady = (sky: Sky) => {
            const skyHeightScaled = sky.height * sky.scaleFactors.height;
            const skyWidthScaled = sky.width * sky.scaleFactors.width;
            setGameContainerDimensions({
                width: skyWidthScaled + "px",
                height: skyHeightScaled + "px",
                visibility: "visible"
            });

            if (sky.scene) {
                sky.scene.selectedCogClickedBlock = initialBlock;
            }
        };

        const handlePlayerOffScreen = () => {
            setBlocksIconState("animation");
        };

        const handlePlayerJumped = () => {
            cogJumpedCounter.current++;
            if (cogJumpedCounter.current === 3) {
                delayedCompletionTimeoutRef.current = window.setTimeout(() => {
                    setBlocksIconState("animation");
                }, 1500);
            }
        };

        EventBus.on('sky-ready', handleSkyReady);
        EventBus.once('player-off-screen', handlePlayerOffScreen);
        EventBus.on('player-jumped', handlePlayerJumped);

        return () => {
            EventBus.removeListener('sky-ready', handleSkyReady);
            EventBus.removeListener('player-off-screen', handlePlayerOffScreen);
            EventBus.removeListener('player-jumped', handlePlayerJumped);
            if (delayedCompletionTimeoutRef.current) {
                window.clearTimeout(delayedCompletionTimeoutRef.current);
            }
        }
    }, [initialBlock]);

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

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

    const blocksIconContainerClasses = [
        styles.doubleColumnContainer,
        blocksIconState === "animation" ? styles.fadeOutAnimation : "",
        blocksIconState === "hidden" ? styles.hide : ""

    ].join(" ");

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

    return (
        <div className={styles.singleColumnContainer}>
            <div className={blocksIconContainerClasses} onAnimationEnd={onBlocksAnimationEnd}>
                <BlocksConnectedIcon className={styles.blocksConnectedIcon} />
                <div className={styles.gameContainer} style={gameContainerDimensions}>
                    <PhaserGame ref={phaserGameRef} />
                </div>
            </div>
            <TickIcon className={tickIconClassNames} onAnimationEnd={onTickIconAnimationEnd} />
        </div>
    );
}
