import { useCallback } from 'react';
import { useActionHandler } from '../../actions/useActionHandler';
import { useProductStore } from '../../../../store/simulation/useProductStore';
import { useSelectedProduct } from '../../../../store/simulation/useSimulationStore';
import { useMaterialStore } from '../../../../store/simulation/useMaterialStore';
import { useArmBotStore } from '../../../../store/simulation/useArmBotStore';
import { useVehicleStore } from '../../../../store/simulation/useVehicleStore';

export function useTriggerHandler() {
    const { handleAction } = useActionHandler();
    const { selectedProduct } = useSelectedProduct();
    const { getEventByTriggerUuid, getEventByModelUuid, getActionByUuid, getModelUuidByActionUuid } = useProductStore();
    const { getArmBotById } = useArmBotStore();
    const { getVehicleById } = useVehicleStore();
    const { setCurrentLocation, setNextLocation, setPreviousLocation, getMaterialById, setIsPaused, setIsVisible, setEndTime } = useMaterialStore();

    const handleTrigger = (trigger: TriggerSchema, action: Action, materialId?: string) => {

        const fromEvent = getEventByTriggerUuid(selectedProduct.productId, trigger.triggerUuid);

        const toEvent = getEventByModelUuid(selectedProduct.productId, trigger.triggeredAsset?.triggeredModel.modelUuid || '');

        if (fromEvent?.type === 'transfer') {
            if (toEvent?.type === 'transfer') {
                // Transfer to Transfer
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {
                        if (material.next) {

                            setPreviousLocation(material.materialId, {
                                modelUuid: material.current.modelUuid,
                                pointUuid: material.current.pointUuid,
                                actionUuid: material.current.actionUuid,
                            })

                            setCurrentLocation(material.materialId, {
                                modelUuid: material.next.modelUuid,
                                pointUuid: material.next.pointUuid,
                                actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                            });

                            setNextLocation(material.materialId, {
                                modelUuid: trigger.triggeredAsset.triggeredModel.modelUuid,
                                pointUuid: trigger.triggeredAsset.triggeredPoint.pointUuid,
                            });
                        }
                        handleAction(action, materialId);
                    }
                }
            } else if (toEvent?.type === 'vehicle') {
                // Transfer to Vehicle
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {

                        // Handle current action of the material
                        handleAction(action, materialId);

                        if (material.next) {
                            const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);
                            const vehicle = getVehicleById(trigger.triggeredAsset?.triggeredModel.modelUuid);

                            setPreviousLocation(material.materialId, {
                                modelUuid: material.current.modelUuid,
                                pointUuid: material.current.pointUuid,
                                actionUuid: material.current.actionUuid,
                            })

                            setCurrentLocation(material.materialId, {
                                modelUuid: material.next.modelUuid,
                                pointUuid: material.next.pointUuid,
                                actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                            });

                            setNextLocation(material.materialId, null);

                            if (action) {

                                if (vehicle) {

                                    if (vehicle.isActive === false && vehicle.state === 'idle' && vehicle.currentLoad < vehicle.point.action.loadCapacity) {

                                        setIsVisible(materialId, false);

                                        // Handle current action from vehicle
                                        handleAction(action, materialId);

                                    } else {

                                        // Event Manager Needed

                                    }
                                }
                            }
                        }
                    }
                }

            } else if (toEvent?.type === 'machine') {
                // Transfer to Machine

            } else if (toEvent?.type === 'roboticArm') {
                // Transfer to Robotic Arm
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {

                        // Handle current action of the material
                        handleAction(action, materialId);

                        if (material.next) {
                            const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);
                            const armBot = getArmBotById(trigger.triggeredAsset?.triggeredModel.modelUuid);

                            setPreviousLocation(material.materialId, {
                                modelUuid: material.current.modelUuid,
                                pointUuid: material.current.pointUuid,
                                actionUuid: material.current.actionUuid,
                            })

                            setCurrentLocation(material.materialId, {
                                modelUuid: material.next.modelUuid,
                                pointUuid: material.next.pointUuid,
                                actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                            });

                            setNextLocation(material.materialId, null);

                            if (action) {

                                if (armBot) {

                                    if (armBot.isActive === false && armBot.state === 'idle') {

                                        setIsPaused(material.materialId, true);

                                        // Handle current action from arm bot
                                        handleAction(action, materialId);

                                    } else {

                                        // Event Manager Needed

                                    }
                                }
                            }
                        }
                    }
                }
            } else if (toEvent?.type === 'storageUnit') {
                // Transfer to Storage Unit

            }
        } else if (fromEvent?.type === 'vehicle') {
            if (toEvent?.type === 'transfer') {
                // Vehicle to Transfer
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {
                        const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);

                        setPreviousLocation(material.materialId, {
                            modelUuid: material.current.modelUuid,
                            pointUuid: material.current.pointUuid,
                            actionUuid: material.current.actionUuid,
                        })

                        setCurrentLocation(material.materialId, {
                            modelUuid: trigger.triggeredAsset.triggeredModel.modelUuid,
                            pointUuid: trigger.triggeredAsset.triggeredPoint.pointUuid,
                            actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                        });

                        setIsVisible(materialId, true);

                        if (action &&
                            action.triggers[0].triggeredAsset?.triggeredModel.modelUuid &&
                            action.triggers[0].triggeredAsset?.triggeredPoint?.pointUuid
                        ) {
                            setNextLocation(material.materialId, {
                                modelUuid: action.triggers[0].triggeredAsset?.triggeredModel.modelUuid,
                                pointUuid: action.triggers[0].triggeredAsset?.triggeredPoint?.pointUuid,
                            });

                            handleAction(action, materialId);
                        }

                    }
                }

            } else if (toEvent?.type === 'vehicle') {
                // Vehicle to Vehicle

            } else if (toEvent?.type === 'machine') {
                // Vehicle to Machine

            } else if (toEvent?.type === 'roboticArm') {
                // Vehicle to Robotic Arm
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {
                        const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);
                        const armBot = getArmBotById(trigger.triggeredAsset?.triggeredModel.modelUuid);

                        setPreviousLocation(material.materialId, {
                            modelUuid: material.current.modelUuid,
                            pointUuid: material.current.pointUuid,
                            actionUuid: material.current.actionUuid,
                        })

                        setCurrentLocation(material.materialId, {
                            modelUuid: trigger.triggeredAsset.triggeredModel.modelUuid,
                            pointUuid: trigger.triggeredAsset.triggeredPoint.pointUuid,
                            actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                        });

                        setNextLocation(material.materialId, null);

                        setIsVisible(materialId, false);

                        if (action && armBot &&
                            action.triggers[0].triggeredAsset?.triggeredModel.modelUuid &&
                            action.triggers[0].triggeredAsset?.triggeredPoint?.pointUuid
                        ) {

                            if (armBot.isActive === false && armBot.state === 'idle') {

                                // Handle current action from arm bot
                                handleAction(action, materialId);

                            } else {

                                // Event Manager Needed

                            }
                        }
                    }
                }

            } else if (toEvent?.type === 'storageUnit') {
                // Vehicle to Storage Unit

            }
        } else if (fromEvent?.type === 'machine') {
            if (toEvent?.type === 'transfer') {
                // Machine to Transfer

            } else if (toEvent?.type === 'vehicle') {
                // Machine to Vehicle

            } else if (toEvent?.type === 'machine') {
                // Machine to Machine

            } else if (toEvent?.type === 'roboticArm') {
                // Machine to Robotic Arm

            } else if (toEvent?.type === 'storageUnit') {
                // Machine to Storage Unit

            }
        } else if (fromEvent?.type === 'roboticArm') {
            if (toEvent?.type === 'transfer') {
                // Robotic Arm to Transfer
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {
                        setIsPaused(material.materialId, false);

                        setPreviousLocation(material.materialId, {
                            modelUuid: material.current.modelUuid,
                            pointUuid: material.current.pointUuid,
                            actionUuid: material.current.actionUuid,
                        })

                        setCurrentLocation(material.materialId, {
                            modelUuid: trigger.triggeredAsset.triggeredModel.modelUuid,
                            pointUuid: trigger.triggeredAsset.triggeredPoint.pointUuid,
                            actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                        });

                        const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);

                        if (action && action.triggers.length > 0 &&
                            action.triggers[0].triggeredAsset?.triggeredModel.modelUuid &&
                            action.triggers[0].triggeredAsset?.triggeredPoint?.pointUuid) {
                            setNextLocation(material.materialId, {
                                modelUuid: action.triggers[0].triggeredAsset?.triggeredModel.modelUuid,
                                pointUuid: action.triggers[0].triggeredAsset?.triggeredPoint?.pointUuid,
                            })
                            handleAction(action, material.materialId);
                        }

                    }
                }

            } else if (toEvent?.type === 'vehicle') {
                // Robotic Arm to Vehicle
                if (materialId && trigger.triggeredAsset && trigger.triggeredAsset.triggeredPoint && trigger.triggeredAsset.triggeredAction) {
                    const material = getMaterialById(materialId);
                    if (material) {

                        setIsPaused(material.materialId, false);

                        const action = getActionByUuid(selectedProduct.productId, trigger.triggeredAsset.triggeredAction.actionUuid);
                        const vehicle = getVehicleById(trigger.triggeredAsset?.triggeredModel.modelUuid);

                        setPreviousLocation(material.materialId, {
                            modelUuid: material.current.modelUuid,
                            pointUuid: material.current.pointUuid,
                            actionUuid: material.current.actionUuid,
                        })

                        setCurrentLocation(material.materialId, {
                            modelUuid: trigger.triggeredAsset.triggeredModel.modelUuid,
                            pointUuid: trigger.triggeredAsset.triggeredPoint.pointUuid,
                            actionUuid: trigger.triggeredAsset?.triggeredAction?.actionUuid,
                        });

                        setNextLocation(material.materialId, null);

                        if (action) {

                            if (vehicle) {

                                if (vehicle.isActive === false && vehicle.state === 'idle' && vehicle.currentLoad < vehicle.point.action.loadCapacity) {

                                    setIsVisible(materialId, false);

                                    // Handle current action from vehicle
                                    handleAction(action, materialId);

                                } else {

                                    // Event Manager Needed

                                }
                            }
                        }

                    }
                }

            } else if (toEvent?.type === 'machine') {
                // Robotic Arm to Machine

            } else if (toEvent?.type === 'roboticArm') {
                // Robotic Arm to Robotic Arm

            } else if (toEvent?.type === 'storageUnit') {
                // Robotic Arm to Storage Unit

            }
        } else if (fromEvent?.type === 'storageUnit') {
            if (toEvent?.type === 'transfer') {
                // Storage Unit to Transfer

            } else if (toEvent?.type === 'vehicle') {
                // Storage Unit to Vehicle

            } else if (toEvent?.type === 'machine') {
                // Storage Unit to Machine

            } else if (toEvent?.type === 'roboticArm') {
                // Storage Unit to Robotic Arm

            } else if (toEvent?.type === 'storageUnit') {
                // Storage Unit to Storage Unit

            }
        }
    }

    const handleFinalAction = (action: Action, materialId?: string) => {
        if (!action) return;

        const modelUuid = getModelUuidByActionUuid(selectedProduct.productId, action.actionUuid);
        if (!modelUuid) return;
        const finalModel = getEventByModelUuid(selectedProduct.productId, modelUuid);
        if (!finalModel) return;

        if (finalModel.type === 'transfer') {
            // Storage Unit to Transfer
            if (!materialId) return;
            const material = getMaterialById(materialId);
            if (material) {
                const currentTime = performance.now();

                setPreviousLocation(material.materialId, {
                    modelUuid: material.current.modelUuid,
                    pointUuid: material.current.pointUuid,
                    actionUuid: material.current.actionUuid,
                })

                setCurrentLocation(material.materialId, {
                    modelUuid: material.next?.modelUuid || '',
                    pointUuid: material.next?.pointUuid || '',
                    actionUuid: action.actionUuid,
                });

                setNextLocation(material.materialId, null);

                setEndTime(material.materialId, currentTime);

                handleAction(action, material.materialId);
            }

        } else if (finalModel.type === 'vehicle') {
            // Storage Unit to Vehicle

        } else if (finalModel.type === 'machine') {
            // Storage Unit to Machine

        } else if (finalModel.type === 'roboticArm') {
            // Storage Unit to Robotic Arm

        } else if (finalModel.type === 'storageUnit') {
            // Storage Unit to Storage Unit

        }

    }

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

        if (action.triggers.length > 0) {

            action.triggers.forEach(trigger => {
                switch (trigger.triggerType) {
                    case 'onStart':
                        break;
                    case 'onComplete':
                        handleTrigger(trigger, action, materialId);
                        break;
                    case 'onStop':
                        break;
                    case 'onError':
                        break;
                    case 'delay':
                        break;
                    default:
                        console.warn(`Unknown trigger type: ${trigger.triggerType}`);
                }
            });
        } else {
            handleFinalAction(action, materialId);
        }
    }, []);

    return {
        triggerPointActions
    };
}