import { useState, useRef, useEffect } from "react";
// import Draggable from "react-draggable";
import styles from "./style.module.css";
import { PosterItem } from "../types";
import { IRefPhaserGame } from "../game/PhaserGame";
import { IRefPhaserGame as IRefPhaserGameTutorial } from "../tutorial-game/PhaserGame";
import { MdKeyboardArrowUp, MdKeyboardArrowDown } from "react-icons/md";
import { MAIN_BLUE } from "../styles/colors";

interface BlockSelector2Props {
    gameRef: React.RefObject<IRefPhaserGame | IRefPhaserGameTutorial>;
    staticBlock: "left" | "right";
    posterItems: PosterItem[];
    staticBlockItem: PosterItem;
    snapPointFactors: number[];
}

export default function BlockSelector2({
    gameRef,
    staticBlock,
    staticBlockItem,
    posterItems,
    snapPointFactors
}: BlockSelector2Props) {
    const containerRef = useRef<HTMLDivElement>(null);
    const [containerHeight, setContainerHeight] = useState(0);
    const [position, setPosition] = useState<{ x: number; y: number } | undefined>();

    const snapPoints = snapPointFactors.map((factor) => containerHeight * factor);


    useEffect(() => {
        if (containerRef.current) {
            setContainerHeight(containerRef.current.offsetHeight);
        }
    }, [containerRef]);

    useEffect(() => {
        const position_ = { x: 0, y: containerHeight * .48 };
        setPosition(position_);

        const closestSnap = position_.y;
        const snapIndex = snapPoints.indexOf(closestSnap);
        if (snapIndex >= 0 && posterItems[snapIndex]) {
            onBlockChange(posterItems[snapIndex]);
        }
    }, [containerHeight]);

    const onBlockChange = (item: PosterItem) => {
        if (!gameRef.current || !gameRef.current.scene) return;
        switch (staticBlock) {
            case "left":
                gameRef.current.scene.selectedCogTiltLeftBlock = item;
                break;
            case "right":
                gameRef.current.scene.selectedCogTiltRightBlock = item;
                break;
        }
        // gameRef.current.scene.registerCogEvents();
    };

    // When drag stops, calculate the closest snap point and update position
    const handleStop = (e: any, data: { x: number; y: number }) => {
        // Find the snap point nearest to data.y
        const closestSnap = snapPoints.reduce((prev, curr) =>
            Math.abs(curr - data.y) < Math.abs(prev - data.y) ? curr : prev
        );
        setPosition({ x: data.x, y: closestSnap });
        // update the game state based on the selected index:
        const snapIndex = snapPoints.indexOf(closestSnap);
        if (snapIndex >= 0 && posterItems[snapIndex]) {
            onBlockChange(posterItems[snapIndex]);
        }
    };

    // Helper to get the current snap index from the current y position.
    const getCurrentSnapIndex = () => {
        if (!position) return 0;
        const index = snapPoints.findIndex((point) => point === position.y);
        if (index === -1) {
            // If not exactly at a snap point, find the nearest one.
            let nearestIndex = 0;
            let smallestDiff = Math.abs(snapPoints[0] - position.y);
            for (let i = 1; i < snapPoints.length; i++) {
                const diff = Math.abs(snapPoints[i] - position.y);
                if (diff < smallestDiff) {
                    smallestDiff = diff;
                    nearestIndex = i;
                }
            }
            return nearestIndex;
        }
        return index;
    };

    const handleArrowUpClick = () => {
        if (!position) return;
        const currentIndex = getCurrentSnapIndex();
        if (currentIndex > 0) {
            const newIndex = currentIndex - 1;
            setPosition({ x: position.x, y: snapPoints[newIndex] });
            if (posterItems[newIndex]) onBlockChange(posterItems[newIndex]);
        }
    };

    const handleArrowDownClick = () => {
        if (!position) return;
        const currentIndex = getCurrentSnapIndex();
        if (currentIndex < snapPoints.length - 1) {
            const newIndex = currentIndex + 1;
            setPosition({ x: position.x, y: snapPoints[newIndex] });
            if (posterItems[newIndex]) onBlockChange(posterItems[newIndex]);
        }
    };

    return (
        <div className={styles.outerContainer}>
            <div className={styles.upArrowContainer} onClick={handleArrowUpClick}>
                <MdKeyboardArrowUp color={MAIN_BLUE} size={40} />
            </div>
            <div ref={containerRef} className={styles.carouselBody}>
                {/* <Draggable
                    axis="y"
                    bounds="parent"
                    position={position}
                    onStop={handleStop}
                > */}
                    <div className={styles.staticBlockItem}>
                        {position && <staticBlockItem.icon className={styles.staticBlockItemIcon} />}
                    </div>
                {/* </Draggable> */}
                {posterItems.map((item, index) => (
                    <div
                        key={index}
                        className={styles.carouselItem}
                    >
                        <item.icon className={styles.carouselItemIcon} />
                    </div>
                ))}
            </div>
            <div className={styles.downArrowContainer} onClick={handleArrowDownClick}>
                <MdKeyboardArrowDown color={MAIN_BLUE} size={40} />
            </div>
        </div>
    );
}