import { useEffect, useCallback } from "react";
import { useDefaultHandler } from "./actionHandler/useDefaultHandler";
import { useSpawnHandler } from "./actionHandler/useSpawnHandler";
import { useSwapHandler } from "./actionHandler/useSwapHandler";
import { useDelayHandler } from "./actionHandler/useDelayHandler";
import { useDespawnHandler } from "./actionHandler/useDespawnHandler";

export function useConveyorActions() {
    const { handleDefault } = useDefaultHandler();
    const { handleSpawn, clearAllSpawns } = useSpawnHandler();
    const { handleSwap } = useSwapHandler();
    const { handleDespawn } = useDespawnHandler();
    const { handleDelay, cleanupDelay } = useDelayHandler();

    const handleDefaultAction = useCallback((action: ConveyorAction, materialId?: string) => {
        handleDefault(action, materialId);
    }, [handleDefault]);

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

    const handleSwapAction = useCallback((action: ConveyorAction, materialId?: string) => {
        handleSwap(action, materialId);
    }, [handleSwap]);

    const handleDelayAction = useCallback((action: ConveyorAction, materialId?: string) => {
        handleDelay(action, materialId);
    }, [handleDelay]);

    const handleDespawnAction = useCallback((action: ConveyorAction, materialId?: string) => {
        handleDespawn(action, materialId)
    }, [handleDespawn]);

    const handleConveyorAction = useCallback((action: ConveyorAction, materialId?: string) => {
        if (!action) return;

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

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

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

    return {
        handleConveyorAction,
        cleanup
    };
}