import { useCallback, useEffect, useRef, useState } from "react";
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 { IRefPhaserGame, PhaserGame } from "../tutorial-game/PhaserGame";
import { EventBus } from "../tutorial-game/EventBus";
import { Mountain } from "../tutorial-game/entities/Mountain";
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 onCogButtonClick = useCallback(() => {
        cogClickedCounter.current++;
        if (cogClickedCounter.current === 3) {
            setBlocksIconState("animation");
            phaserGameRef.current?.game?.destroy(true);
        }
    }, []);

    // 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(() => {
        EventBus.on('mountain-ready', (mountain: Mountain) => {
            const mountainHeightScaled = mountain.height * mountain.scaleFactors.height;
            const mountainWidthScaled = mountain.width * mountain.scaleFactors.width;
            setGameContainerDimensions({
                width: mountainWidthScaled + "px",
                height: mountainHeightScaled + "px",
                visibility: "visible"
            });

            if (mountain.scene) {
                // mountain.scene.currentlySectedBlock = initialBlock;
            }
        });

        EventBus.once('player-off-screen', () => {
            setBlocksIconState("animation");
            phaserGameRef.current?.game?.destroy(true);
        });

        EventBus.on('player-jumped', () => {
            cogJumpedCounter.current++;
            if (cogJumpedCounter.current === 3) {
                setTimeout(() => {
                    setBlocksIconState("animation");
                    phaserGameRef.current?.game?.destroy(true);
                }, 1500);
            }
        });

        return () => {
            EventBus.removeListener('mountain-ready');
            EventBus.removeListener('player-off-screen');
            EventBus.removeListener('player-jumped');
        }
    }, [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>
    );
}
