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 { PosterItem } from "../types";
import TiltGauge, { TiltGaugeHandle } from "../TiltGauge";

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

export function GaugePhase({ nextPhase, BlocksConnectedIcon, initialBlock, blocksGif }: Props) {
    const tiltGaugeRef = useRef<TiltGaugeHandle>(null);
    const [tickIconState, setTickIconState] = useState<"hidden" | "visible" | "animation">("hidden");
    const [blocksIconState, setBlocksIconState] = useState<"hidden" | "visible" | "animation">("visible");

    useEffect(() => {
        if (blocksIconState !== "visible") {
            return;
        }
        const DUMMY_MOVEMENT = false; // set to true to simulate movement for testing without a cog
        const intervalId = setInterval(() => {
            const connectedCog = getConnectedCog();
            if (!connectedCog) {
                if (DUMMY_MOVEMENT) {
                    // simulate some movement for testing without a cog
                    const time = Date.now() / 1000;
                    const simulatedRawTilt = Math.sin(time) * 1.2; // oscillate between -1.4 and 1.4
                    const normalisedTilt = normaliseTiltScore(simulatedRawTilt, initialBlock.block);
                    tiltGaugeRef.current?.setScore(normalisedTilt);
                    if (normalisedTilt > 0.95) {
                        setBlocksIconState((prev) => prev === "visible" ? "animation" : prev);
                    }
                }
                return;
            }
            const cog = connectedCog as Cog;
            // @ts-ignore remove ts ignore once you update the webapptypes -- steeringDetection is not in the types yet
            if (!cog.publishedDataAnalyser.steeringDetection.isHeldAsSteeringWheelProp) {
                return;
            }

            const { ay, ax } = cog.raftStateInfo.accelerometer;
            const rawTilt = Math.atan2(ay, -ax) - Math.PI / 2; // radians, zero=right, CCW+
            const normalisedTilt = normaliseTiltScore(rawTilt, initialBlock.block);

            tiltGaugeRef.current?.setScore(normalisedTilt);

            if (normalisedTilt > 0.95) {
                setBlocksIconState((prev) => prev === "visible" ? "animation" : prev);
            }
        }, 200);

        return () => clearInterval(intervalId);
    }, [blocksIconState, initialBlock.block]);

    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.blocksGifContainer}>
                    <img src={blocksGif} alt="Blocks Gif" className={styles.blocksGif} />
                </div>
                <div className={styles.gaugeContainer} style={{}}>
                    <TiltGauge ref={tiltGaugeRef} title="" />
                </div>
            </div>
            <TickIcon className={tickIconClassNames} onAnimationEnd={onTickIconAnimationEnd} />
        </div>
    );
}

function normaliseTiltScore(rawTilt: number, block: PosterItem["block"]) {
    const clampedTilt = Math.max(-1.4, Math.min(1.4, rawTilt));

    if (block === "tiltleft") {
        if (clampedTilt >= 0) {
            return 0;
        }
        return Math.min(1, Math.abs(clampedTilt) / 1.4);
    }

    if (block === "tiltright") {
        if (clampedTilt <= 0) {
            return 0;
        }
        return Math.min(1, clampedTilt / 1.4);
    }

    return 0;
}
