import { useEffect, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import { usePauseButtonStore, usePlayButtonStore, useResetButtonStore } from '../../../../store/usePlayButtonStore';
import { useSceneContext } from '../../../scene/sceneContext';

type ArmBotCallback = {
    armBotId: string;
    callback: () => void;
};

export function useArmBotEventManager() {
    const {armBotStore} = useSceneContext();
    const { getArmBotById } = armBotStore();
    const callbacksRef = useRef<ArmBotCallback[]>([]);
    const isMonitoringRef = useRef(false);
    const { isPlaying } = usePlayButtonStore();
    const { isPaused } = usePauseButtonStore();
    const { isReset } = useResetButtonStore();

    useEffect(() => {
        if (isReset) {
            callbacksRef.current = [];
        }
    }, [isReset])

    // Add a new armbot to monitor
    const addArmBotToMonitor = (armBotId: string, callback: () => void) => {
        // Avoid duplicates
        if (!callbacksRef.current.some((entry) => entry.armBotId === armBotId)) {
            callbacksRef.current.push({ armBotId, callback });
        }

        // Start monitoring if not already running
        if (!isMonitoringRef.current) {
            isMonitoringRef.current = true;
        }
    };

    // Remove an armbot from monitoring (e.g., when unmounted)
    const removeArmBotFromMonitor = (armBotId: string) => {
        callbacksRef.current = callbacksRef.current.filter(
            (entry) => entry.armBotId !== armBotId
        );

        // Stop monitoring if no more armbots to track
        if (callbacksRef.current.length === 0) {
            isMonitoringRef.current = false;
        }
    };

    // Check armbot states every frame
    useFrame(() => {
        if (!isMonitoringRef.current || callbacksRef.current.length === 0 || !isPlaying || isPaused) return;

        callbacksRef.current.forEach(({ armBotId, callback }) => {
            const armBot = getArmBotById(armBotId);
            if (armBot?.isActive === false && armBot?.state === 'idle') {
                callback();
                removeArmBotFromMonitor(armBotId); // Remove after triggering
            }
        });
    });

    // Cleanup on unmount (optional, since useFrame auto-cleans)
    useEffect(() => {
        return () => {
            callbacksRef.current = [];
            isMonitoringRef.current = false;
        };
    }, []);

    return {
        addArmBotToMonitor,
        removeArmBotFromMonitor,
    };
}