import React, { useEffect } from 'react'
import { useMaterialStore } from '../../../../../store/simulation/useMaterialStore';
import { useConveyorStore } from '../../../../../store/simulation/useConveyorStore';
import { useResetButtonStore } from '../../../../../store/usePlayButtonStore';
import { findConveyorInSequences } from '../../../simulator/functions/findConveyorInSequences';
import { useSelectedProduct } from '../../../../../store/simulation/useSimulationStore';
import { useProductStore } from '../../../../../store/simulation/useProductStore';

function ConveyorInstance({ conveyor }: { conveyor: ConveyorStatus }) {
    const { getProductById } = useProductStore();
    const { selectedProduct } = useSelectedProduct();
    const { materials, getMaterialsByCurrentModelUuid } = useMaterialStore();
    const { isReset } = useResetButtonStore();
    const { setConveyorPaused } = useConveyorStore();

    useEffect(() => {
        const product = getProductById(selectedProduct.productId);
        if (!product) return;

        const sequenceInfo = findConveyorInSequences(product, conveyor.modelUuid);
        if (!sequenceInfo) return;

        const { currentSubSequence } = sequenceInfo;
        const conveyorMaterials = getMaterialsByCurrentModelUuid(conveyor.modelUuid);

        if (conveyorMaterials && conveyorMaterials.length > 0) {
            const shouldPauseSubsequence = currentSubSequence.some(subConveyor => {
                if (subConveyor.type !== 'transfer') return false;
                const subMaterials = getMaterialsByCurrentModelUuid(subConveyor.modelUuid);
                return subMaterials?.some(m => m.isPaused) ?? false;
            });

            currentSubSequence.forEach(subConveyor => {
                if (subConveyor.type === 'transfer') {
                    setConveyorPaused(subConveyor.modelUuid, shouldPauseSubsequence);
                }
            });
        }
    }, [materials, conveyor.modelUuid, getMaterialsByCurrentModelUuid, setConveyorPaused, isReset, selectedProduct.productId, getProductById]);

    return null;
}

export default React.memo(ConveyorInstance);