import { useCallback } from "react";
import { useSceneContext } from "../../../../scene/sceneContext";
import { useProductContext } from "../../../products/productContext";

export function usePickAndPlaceHandler() {
    const { materialStore, armBotStore, productStore } = useSceneContext();
    const { selectedProductStore } = useProductContext();
    const { getMaterialById } = materialStore();
    const { addCurrentAction } = armBotStore();
    const { getModelUuidByActionUuid } = productStore();
    const { selectedProduct } = selectedProductStore();

    const pickAndPlaceLogStatus = (materialUuid: string, status: string) => {
        echo.warn(`${materialUuid}, ${status}`);
    }

    const handlePickAndPlace = useCallback((action: RoboticArmAction, materialId?: string) => {
        if (!action || action.actionType !== 'pickAndPlace' || !materialId) return;

        const material = getMaterialById(materialId);
        if (!material) return;

        const modelUuid = getModelUuidByActionUuid(selectedProduct.productUuid, action.actionUuid);

        if (!modelUuid) return;

        addCurrentAction(
            modelUuid,
            action.actionUuid,
            material.materialType,
            material.materialId
        );

        pickAndPlaceLogStatus(material.materialName, `is going to be picked by armBot ${modelUuid}`);

    }, [getMaterialById, getModelUuidByActionUuid, selectedProduct.productUuid, addCurrentAction]);

    return {
        handlePickAndPlace,
    };
}