import { useEffect, useCallback, useRef } from "react";
import { useSpawnHandler } from "./actionHandler/useSpawnHandler";

export function useConveyorActions() {
    const { handleSpawn, clearCurrentSpawn } = useSpawnHandler();

    const handleDefaultAction = useCallback((action: ConveyorAction) => {
        // console.log(`Default conveyor action ${action.actionUuid}`);
    }, []);

    const handleSpawnAction = useCallback((action: ConveyorAction) => {
        handleSpawn(action);
    }, [handleSpawn]);

    const handleSwapAction = useCallback((action: ConveyorAction) => {
        console.log(`Swapping to material ${action.material}`);
    }, []);

    const handleDelayAction = useCallback((action: ConveyorAction) => {
        const delayMs = (action.delay || 0) * 1000;
        console.log(`Delaying for ${delayMs}ms`);
    }, []);

    const handleDespawnAction = useCallback((action: ConveyorAction) => {
        console.log(`Despawning material`);
    }, []);

    const handleConveyorAction = useCallback((action: ConveyorAction) => {
        if (!action) return;

        switch (action.actionType) {
            case 'default':
                handleDefaultAction(action);
                break;
            case 'spawn':
                handleSpawnAction(action);
                break;
            case 'swap':
                handleSwapAction(action);
                break;
            case 'delay':
                handleDelayAction(action);
                break;
            case 'despawn':
                handleDespawnAction(action);
                break;
            default:
                console.warn(`Unknown conveyor action type: ${action.actionType}`);
        }
    }, [handleDefaultAction, handleSpawnAction, handleSwapAction, handleDelayAction, handleDespawnAction]);

    const cleanup = useCallback(() => {
        clearCurrentSpawn();
    }, [clearCurrentSpawn]);

    useEffect(() => {
        return () => {
            cleanup();
        };
    }, [cleanup]);

    return {
        handleConveyorAction,
        cleanup
    };
}