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 { Mountain } from "../tutorial-game/entities/Mountain";
import { PosterItem } from "../types";
import PlayScene from "../tutorial-game/scenes/PlayScene";

import { ReactComponent as OnTiltLeft } from "../assets/blocks/ontiltleft.svg";
import { ReactComponent as OnTiltRight } from "../assets/blocks/ontiltright.svg";

import { ReactComponent as ForwardIcon } from "../assets/blocks/forward.svg";
import { ReactComponent as BackwardIcon } from "../assets/blocks/backward.svg";

import { ReactComponent as NowhereIcon } from "../assets/blocks/nowhere.svg";

import BlockSelector4 from "../block-selector-4";
import { setSelectedBlockFromTutorialForLeft, setSelectedBlockFromTutorialForRight, selectedBlockFromTutorialForLeft, selectedBlockFromTutorialForRight } from "../utils/selected-blocks-from-tutorial";

import playImage from '../assets/playbutton.svg';

const posterItemsLeft: PosterItem[] = [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
];
const posterItemsRight: PosterItem[] = [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: BackwardIcon, block: "moveleft", execute: async () => true },
];

const staticBlockItemUp: PosterItem = { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true };

const staticBlockItemDown: PosterItem = { icon: OnTiltRight, block: "ontiltright", execute: async () => true };

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

export function Phase3({ nextPhase }: Props) {
    const [gameContainerDimensions, setGameContainerDimensions] = useState({ width: "40vw", height: "60vh", visibility: "hidden" } as React.CSSProperties);
    const [posterItemsLeftState, setPosterItemsLeftState] = useState<PosterItem[]>([]);
    const [posterItemsRightState, setPosterItemsRightState] = useState<PosterItem[]>([]);
    const [isSceneReady, setIsSceneReady] = useState(false);
    const [tickIconState, setTickIconState] = useState<"hidden" | "visible" | "animation">("hidden");
    const [blocksIconState, setBlocksIconState] = useState<"hidden" | "visible" | "animation">("visible");
    const phaserGameRef = useRef<IRefPhaserGame>(null);
    const [showAreYouReady, setShowAreYouReady] = useState(false);

    useEffect(() => {
        // setting a timeinterval to check every 100ms if both controls have been set
        const checkControlsSet = setInterval(() => {
            const leftClickBlock = phaserGameRef.current?.scene?.selectedCogTiltLeftBlock?.block;
            const rightClickBlock = phaserGameRef.current?.scene?.selectedCogTiltRightBlock?.block
            if (
                (leftClickBlock === "moveright" ||
                    leftClickBlock === "moveleft") &&
                (rightClickBlock === "moveright" ||
                    rightClickBlock === "moveleft")
            ) {
                setShowAreYouReady(true);
                clearInterval(checkControlsSet);
            }
        }, 100);

        return () => {
            clearInterval(checkControlsSet);
        };
    }, []);

    useEffect(() => {
        // setting the poster items for click and no click IF they exist in the game
        const leftClickBlock = selectedBlockFromTutorialForLeft;
        const rightClickBlock = selectedBlockFromTutorialForRight;
        if (leftClickBlock) {
            const index = posterItemsLeft.findIndex(item => item.block === leftClickBlock.block);
            if (index !== -1) {
                const selectedBlock = posterItemsLeft[index];
                const middleIndex = Math.floor(posterItemsLeft.length / 2);
                // remove the selected block from the poster items
                const newposterItemsClick = posterItemsLeft.filter(item => item.block !== selectedBlock.block);
                // add the selected block to the middle of the poster items
                newposterItemsClick.splice(middleIndex, 0, selectedBlock);
                setPosterItemsLeftState(newposterItemsClick);
            }
        } else {
            // if the left block is not set, we set the poster items to the default ones
            setPosterItemsLeftState(posterItemsLeft);
        }
        if (rightClickBlock) {
            const index = posterItemsRight.findIndex(item => item.block === rightClickBlock.block);
            if (index !== -1) {
                const selectedBlock = posterItemsRight[index];
                const middleIndex = Math.floor(posterItemsRight.length / 2);
                // remove the selected block from the poster items
                const newposterItemsRight = posterItemsRight.filter(item => item.block !== selectedBlock.block);
                // add the selected block to the middle of the poster items
                newposterItemsRight.splice(middleIndex, 0, selectedBlock);
                setPosterItemsRightState(newposterItemsRight);
            }
        } else {
            // if the right click block is not set, we set the poster items to the default ones
            setPosterItemsRightState(posterItemsRight);
        }

    }, []);


    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"
            });
            setIsSceneReady(true);
        });

        EventBus.on('current-scene-ready', (scene: PlayScene) => {
            setTimeout(() => {
                scene.physics.world.setBounds(0, 0, scene.scale.width, scene.scale.height);
                scene.player?.setCollideWorldBounds(true);
                // scene.spawnFlags();
                // const flag1 = scene.flags?.getChildren()[0];
                // Phaser.Actions.SetX(scene.flags?.getChildren() || [], 50 * (scene.mountain?.scaleFactors?.width || 0));
                // if (flag1) Phaser.Actions.SetY([flag1], 1200 * (scene.mountain?.scaleFactors?.height || 0));
            }, 1000);
        });

        // EventBus.on('flags-collected', (scene: PlayScene) => {
        //     if (scene.collectedFlags === 2) {
        //         setShowAreYouReady(true);
        //         // setTimeout(() => {
        //         // setBlocksIconState("animation");
        //         // phaserGameRef.current?.game?.destroy(true);
        //         // }, 1500);
        //     }
        // });

        return () => {
            // EventBus.removeListener('flags-collected');
            EventBus.removeListener('mountain-ready');
            EventBus.removeListener('current-scene-ready');
            EventBus.removeListener('player-jumped');
        }
    }, []);

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

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

    const blocksIconContainerClasses = [
        styles.singleColumnContainer,
        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(" ");

    const handleAreYouReadyClick = () => {
        setBlocksIconState("animation");
        phaserGameRef.current?.game?.destroy(true);
        setShowAreYouReady(false);
        if (phaserGameRef.current && phaserGameRef.current.scene) {
            setSelectedBlockFromTutorialForLeft(phaserGameRef.current.scene.selectedCogTiltLeftBlock);
            setSelectedBlockFromTutorialForRight(phaserGameRef.current.scene.selectedCogTiltRightBlock);
        }
    };

    return (
        <div className={styles.singleColumnContainer}>
            {showAreYouReady && <div className={styles.areYouReadyContainer}>
                <img src={playImage} alt="Play" className={styles.playButton} onClick={handleAreYouReadyClick} />
            </div>}
            <div className={blocksIconContainerClasses} onAnimationEnd={onBlocksAnimationEnd}>
                <div className={styles.doubleBlockSelectorContainer}>
                    {!!posterItemsLeftState.length && <BlockSelector4 gameRef={phaserGameRef} staticBlock="left" posterItems={posterItemsLeftState} staticBlockItem={staticBlockItemUp} />}
                    {!!posterItemsRightState.length && <BlockSelector4 gameRef={phaserGameRef} staticBlock="right" posterItems={posterItemsRightState} staticBlockItem={staticBlockItemDown} />}
                </div>
                <div className={styles.gameContainer} style={gameContainerDimensions}>
                    <PhaserGame ref={phaserGameRef} />
                </div>
            </div>
            <TickIcon className={tickIconClassNames} onAnimationEnd={onTickIconAnimationEnd} />
        </div>
    );
}
