import { useEffect } from 'react';
import { determineExecutionMachineSequences } from '../../simulator/functions/determineExecutionMachineSequences';
import { useInputValues, useMachineCount, useMachineDowntime, useMachineUptime, useMaterialCycle, useProcessBar, useThroughPutData } from '../../../../store/builder/store';
import { usePlayButtonStore } from '../../../../store/usePlayButtonStore';
import { useSceneContext } from '../../../scene/sceneContext';
import { useProductContext } from '../../products/productContext';

export default function ThroughPutData() {
    const { materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, productStore } = useSceneContext();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { products, getProductById } = productStore();
    const { armBots } = armBotStore();
    const { vehicles } = vehicleStore();
    const { machines } = machineStore();
    const { conveyors } = conveyorStore();
    const { storageUnits } = storageUnitStore();
    const { materialHistory, materials } = materialStore();
    const { machineCount, setMachineCount } = useMachineCount();
    const { machineActiveTime, setMachineActiveTime } = useMachineUptime();
    const { machineIdleTime, setMachineIdleTime } = useMachineDowntime();
    const { materialCycleTime, setMaterialCycleTime } = useMaterialCycle();
    const { setProcessBar } = useProcessBar();
    const { setThroughputData } = useThroughPutData()
    const { isPlaying } = usePlayButtonStore();
    const { inputValues } = useInputValues();

    // Setting machine count
    let totalItems = 0;
    let totalActiveTime = 0;
    let totalIdleTime = 0

    useEffect(() => {
        if (!isPlaying) {
            totalActiveTime = 0;
            totalItems = 0;
            totalIdleTime = 0;
            setMachineCount(0);
            setMachineActiveTime(0);
            setMachineIdleTime(0);
            setMaterialCycleTime(0);
            setProcessBar([]);
            setThroughputData(0);
        }
    }, [isPlaying])

    useEffect(() => {
        if (isPlaying) {
            let process: any = [];
            const fetchProductSequenceData = async () => {
                const productData = getProductById(selectedProduct.productUuid);
                if (productData) {
                    const productSequenceData = await determineExecutionMachineSequences([productData])
                    if (productSequenceData?.length > 0) {
                        productSequenceData.forEach((sequence) => {
                            sequence.forEach((item) => {
                                if (item.type === "roboticArm") {
                                    armBots.filter(arm => arm.modelUuid === item.modelUuid)
                                        .forEach(arm => {
                                            if (arm.activeTime > 0) {
                                                process.push({ modelid: arm.modelUuid, modelName: arm.modelName, activeTime: arm?.activeTime })
                                                totalActiveTime += arm.activeTime;
                                            }
                                            if (arm.idleTime > 0) {
                                                totalIdleTime += arm.idleTime;
                                            }
                                        });
                                } else if (item.type === "vehicle") {
                                    vehicles.filter(vehicle => vehicle.modelUuid === item.modelUuid)
                                        .forEach(vehicle => {
                                            if (vehicle.activeTime > 0) {
                                                process.push({ modelid: vehicle.modelUuid, modelName: vehicle.modelName, activeTime: vehicle?.activeTime })

                                                totalActiveTime += vehicle.activeTime;
                                            }
                                            if (vehicle.idleTime > 0) {
                                                totalIdleTime += vehicle.idleTime;
                                            }
                                        });
                                } else if (item.type === "machine") {
                                    machines.filter(machine => machine.modelUuid === item.modelUuid)
                                        .forEach(machine => {
                                            if (machine.activeTime > 0) {
                                                process.push({ modelid: machine.modelUuid, modelName: machine.modelName, activeTime: machine?.activeTime })
                                                totalActiveTime += machine.activeTime;
                                            }
                                            if (machine.idleTime > 0) {
                                                totalIdleTime += machine.idleTime;
                                            }
                                        });
                                } else if (item.type === "transfer") {
                                    conveyors.filter(conveyor => conveyor.modelUuid === item.modelUuid)
                                        .forEach(conveyor => {
                                            if (conveyor.activeTime > 0) {
                                                // totalActiveTime += conveyor.activeTime;
                                            }
                                        });
                                } else if (item.type === "storageUnit") {
                                    storageUnits.filter(storage => storage.modelUuid === item.modelUuid)
                                        .forEach(storage => {
                                            if (storage.activeTime > 0) {
                                                // totalActiveTime += storage.activeTime;
                                                // 
                                            }
                                        });
                                }
                            });

                            totalItems += sequence.length;
                        });


                        setMachineCount(totalItems);
                        setMachineActiveTime(totalActiveTime);
                        setMachineIdleTime(totalIdleTime);
                        let arr = process.map((item: any) => ({
                            name: item.modelName,
                            completed: Math.round((item.activeTime / totalActiveTime) * 100)
                        }));
                        setProcessBar(arr);
                    }
                }
            };

            fetchProductSequenceData();
        }
        // if (materialCycleTime <= 0) return
    }, [products, selectedProduct?.productUuid, getProductById, setMachineCount, materialCycleTime, armBots, vehicles, machines]);

    useEffect(() => {
        let timeoutId: ReturnType<typeof setTimeout>;
        async function getMachineActive() {
            const productData = getProductById(selectedProduct.productUuid);
            let anyArmActive;
            let anyVehicleActive;
            let anyMachineActive;
            if (productData) {
                const productSequenceData = await determineExecutionMachineSequences([productData]);
                if (productSequenceData?.length > 0) {
                    productSequenceData.forEach(sequence => {
                        sequence.forEach(item => {
                            if (item.type === "roboticArm") {
                                armBots
                                    .filter(arm => arm.modelUuid === item.modelUuid)
                                    .forEach(arm => {
                                        if (arm.isActive) {
                                            anyArmActive = true;
                                        } else {
                                            anyArmActive = false;
                                        }
                                    });
                            }
                            if (item.type === "vehicle") {
                                vehicles
                                    .filter(vehicle => vehicle.modelUuid === item.modelUuid)
                                    .forEach(vehicle => {
                                        if (vehicle.isActive) {
                                            anyVehicleActive = true;
                                        } else {
                                            anyVehicleActive = false;
                                        }
                                    });
                            }
                            if (item.type === "machine") {
                                machines
                                    .filter(machine => machine.modelUuid === item.modelUuid)
                                    .forEach(machine => {
                                        if (machine.isActive) {
                                            anyMachineActive = true;
                                        } else {
                                            anyMachineActive = false;
                                        }
                                    });
                            }
                        });
                    });
                }
            }

            const allInactive = !anyArmActive && !anyVehicleActive && !anyMachineActive;
            if (materials.length >= 0 && materialHistory.length > 0) {

                let totalCycleTimeSum = 0;
                let cycleCount = 0;

                materialHistory.forEach((material) => {
                    const start = material.material.startTime ?? 0;
                    const end = material.material.endTime ?? 0;
                    if (start === 0 || end === 0) return;

                    const totalCycleTime = (end - start) / 1000; // Convert milliseconds to seconds
                    totalCycleTimeSum += totalCycleTime;
                    cycleCount++;
                });

                if (cycleCount > 0) {
                    const averageCycleTime = totalCycleTimeSum / cycleCount;
                    setMaterialCycleTime(Number(averageCycleTime.toFixed(2)));
                }
            }
        }
        if (isPlaying) {
            timeoutId = setTimeout(() => {
                getMachineActive();
            }, 1500);
        }

        return () => {
            if (timeoutId) clearTimeout(timeoutId);
        };
    }, [armBots, materials, materialHistory, machines, vehicles, selectedProduct?.productUuid])

    useEffect(() => {
        const shiftLength = parseFloat(inputValues["Shift length"]);
        const shiftsPerDay = parseFloat(inputValues["Shifts / day"]);
        const yieldRate = parseFloat(inputValues["Yield rate"]);

        if (shiftLength > 0 && materialCycleTime > 0 && machineCount > 0 && isPlaying) {
            const Units_per_shift = (shiftLength * 60) / (materialCycleTime / 60);

            const Throughput_per_day = Units_per_shift * shiftsPerDay * (yieldRate / 100);
            setThroughputData(Number(Throughput_per_day.toFixed(2))); // Keep as number
        }
    }, [materialCycleTime, machineCount, isPlaying, inputValues]);

    return (
        <>
        </>
    );
}
