import { useRef, useEffect } from "react";
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 BlockSelector4Props {
    gameRef: React.RefObject<IRefPhaserGame | IRefPhaserGameTutorial>;
    staticBlock: "left" | "right";
    posterItems: PosterItem[];
    staticBlockItem: PosterItem;
}

export default function BlockSelector4({
    gameRef,
    staticBlock,
    staticBlockItem,
    posterItems,
}: BlockSelector4Props) {
    const containerRef = useRef<HTMLDivElement>(null);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const staticBlockRef = useRef<HTMLDivElement>(null);
    const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    const itemHeight = 50;

    // start at the middle item
    useEffect(() => {
        if (scrollContainerRef.current) {
            scrollContainerRef.current.scrollTop = posterItems.length * itemHeight / 2;
        }
    }, [posterItems]);

    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;
        }
    }

    const getSnappedItem = (): PosterItem | null => {
        if (!staticBlockRef.current || !scrollContainerRef.current) return null;
        const staticRect = staticBlockRef.current.getBoundingClientRect();
        const staticCenterY = staticRect.top + staticRect.height / 2;

        const items = scrollContainerRef.current.querySelectorAll(`.${styles.carouselItem}`);
        let closestEl: Element | null = null;
        let minDist = Infinity;
        items.forEach(el => {
            const r = el.getBoundingClientRect();
            const dist = Math.abs(staticCenterY - (r.top + r.height / 2));
            if (dist < minDist) {
                minDist = dist;
                closestEl = el;
            }
        });

        if (closestEl) {
            const idx = parseInt((closestEl as Element).getAttribute("data-index") || "", 10);
            return posterItems[idx];
        }
        return null;
    };

    const handleScroll = () => {
        if (scrollTimeoutRef.current) {
            clearTimeout(scrollTimeoutRef.current);
        }
        scrollTimeoutRef.current = setTimeout(() => {
            const snapped = getSnappedItem();
            if (snapped) onBlockChange(snapped);
        }, 150);
    };

    const scrollByItem = (dir: "up" | "down") => {
        const el = scrollContainerRef.current;
        if (!el) return;
        const delta = dir === "up" ? -itemHeight : itemHeight;
        // scrollBy with smooth behavior
        el.scrollBy({ top: delta, behavior: "smooth" });
    };

    return (
        <div className={styles.outerContainer}>
            <div onClick={() => scrollByItem("down")} className={styles.upArrowContainer}>
                <MdKeyboardArrowUp color={MAIN_BLUE} size={40} />
            </div>
            <div ref={containerRef} className={styles.carouselBody}>
                {/* static block stays fixed in the middle */}
                <div ref={staticBlockRef} className={styles.staticBlockItem}>
                    <staticBlockItem.icon className={styles.staticBlockItemIcon} />
                </div>
                <div
                    ref={scrollContainerRef}
                    className={styles.scrollContainer}
                    onScroll={handleScroll}
                    style={{
                        overflowY: "auto",
                        paddingTop: (itemHeight * 2 - 2),
                        paddingBottom: (itemHeight * 2 - 2),
                    }}
                >

                    {posterItems.map((item, index) => (
                        <div
                            key={index + item.block}
                            data-index={index}
                            className={styles.carouselItem}
                            style={{ height: itemHeight }}
                        >
                            <item.icon className={styles.carouselItemIcon} />
                        </div>
                    ))}

                </div>
            </div>
            <div onClick={() => scrollByItem("up")} className={styles.downArrowContainer}>
                <MdKeyboardArrowDown color={MAIN_BLUE} size={40} />
            </div>
        </div>
    );
}