import React, { useEffect, useRef, useState } from 'react';
import { useSelectedProduct } from '../../../../store/simulation/useSimulationStore';
import { useProductStore } from '../../../../store/simulation/useProductStore';
import { determineExecutionMachineSequences } from '../../simulator/functions/determineExecutionMachineSequences';
import { useArmBotStore } from '../../../../store/simulation/useArmBotStore';
import { useMachineCount, useMachineUptime, useMaterialCycle, useThroughPutData } from '../../../../store/builder/store';
import { useVehicleStore } from '../../../../store/simulation/useVehicleStore';
import { useMachineStore } from '../../../../store/simulation/useMachineStore';
import { useConveyorStore } from '../../../../store/simulation/useConveyorStore';
import { useStorageUnitStore } from '../../../../store/simulation/useStorageUnitStore';
import { useMaterialStore } from '../../../../store/simulation/useMaterialStore';
import { usePauseButtonStore, usePlayButtonStore } from '../../../../store/usePlayButtonStore';

export default function ThroughPutData() {
    const { selectedProduct } = useSelectedProduct();
    const { products, getProductById } = useProductStore();
    const { armBots, incrementActiveTime, incrementIdleTime } = useArmBotStore();
    const { vehicles } = useVehicleStore();
    const { machines } = useMachineStore();
    const { conveyors } = useConveyorStore();
    const { storageUnits } = useStorageUnitStore();
    const { materials } = useMaterialStore();

    const { machineCount, setMachineCount } = useMachineCount();
    const { machineActiveTime, setMachineActiveTime } = useMachineUptime();

    const { materialCycleTime, setMaterialCycleTime } = useMaterialCycle();

    // const [totalActiveTime, setTotalActiveTime] = useState(0);
    const { setThroughputData } = useThroughPutData() // <=== ADD THIS
    const { isPlaying } = usePlayButtonStore();

    // Setting machine count
    useEffect(() => {
        if (materialCycleTime < 0) return
        // console.log('materialCycleTime: ', materialCycleTime);
        const fetchProductSequenceData = async () => {
            const productData = getProductById(selectedProduct.productId);
            if (productData) {
                const productSequenceData = await determineExecutionMachineSequences([productData]);
                // console.log('productSequenceData: ', productSequenceData);

                if (productSequenceData?.length > 0) {
                    let totalItems = 0;
                    let totalActiveTime = 0;

                    productSequenceData.forEach((sequence) => {
                        // console.log('sequence: ', sequence);

                        sequence.forEach((item) => {
                            if (item.type === "roboticArm") {
                                armBots.filter(arm => arm.modelUuid === item.modelUuid)
                                    .forEach(arm => {

                                        if (arm.activeTime >= 0) {
                                            totalActiveTime += arm.activeTime;
                                        }
                                    });
                            } else if (item.type === "vehicle") {
                                vehicles.filter(vehicle => vehicle.modelUuid === item.modelUuid)
                                    .forEach(vehicle => {

                                        if (vehicle.activeTime >= 0) {
                                            //  totalActiveTime += vehicle.activeTime;
                                            // totalActiveTime += 10;
                                        }
                                    });
                            } else if (item.type === "machine") {
                                machines.filter(machine => machine.modelUuid === item.modelUuid)
                                    .forEach(machine => {
                                        if (machine.activeTime >= 0) {
                                            // totalActiveTime += machine.activeTime;
                                            // totalActiveTime += 12;
                                        }
                                    });
                            } else if (item.type === "transfer") {
                                conveyors.filter(conveyor => conveyor.modelUuid === item.modelUuid)
                                    .forEach(conveyor => {
                                        if (conveyor.activeTime >= 0) {
                                            // totalActiveTime += conveyor.activeTime;
                                            // totalActiveTime += 7;
                                        }
                                    });
                            } else if (item.type === "storageUnit") {
                                storageUnits.filter(storage => storage.modelUuid === item.modelUuid)
                                    .forEach(storage => {
                                        if (storage.activeTime >= 0) {
                                            // totalActiveTime += storage.activeTime;
                                            // totalActiveTime += 9;
                                        }
                                    });
                            }
                        });

                        totalItems += sequence.length;
                    });

                    setMachineCount(totalItems);
                    setMachineActiveTime(totalActiveTime);

                }
            }
        };

        fetchProductSequenceData();
    }, [products, selectedProduct, getProductById, setMachineCount, isPlaying, armBots, materialCycleTime]);

    // Setting material cycle time
    useEffect(() => {
        materials.map((material) => {
            // console.log('material: ', material);
            // const totalCycleTime = material.endTime - material.startTime;//dynamic
            const staticStartTime = 50;
            const staticEndTime = 100;
            const totalCycleTime = staticEndTime - staticStartTime;
            setMaterialCycleTime(totalCycleTime)

        })
    }, [materials]);


    useEffect(() => {
        if (machineActiveTime > 0 && materialCycleTime > 0 && machineCount > 0) {
            const avgProcessTime = (machineActiveTime / materialCycleTime) * 100; // % value
            const throughput = (3600 / materialCycleTime) * machineCount * (avgProcessTime / 100); // ✅ division by 100
            setThroughputData(throughput.toFixed(2)); // Set the throughput data in the store

            // console.log('---Throughput Results---');
            // console.log('Total Active Time:', machineActiveTime);
            // console.log('Material Cycle Time:', materialCycleTime);
            // console.log('Machine Count:', machineCount);
            // console.log('Average Process Time (%):', avgProcessTime);
            // console.log('Calculated Throughput:', throughput);
        }
    }, [machineActiveTime, materialCycleTime, machineCount]);



    return (
        <>
        </>
    );
}



    // useEffect(() => {
    //     if (!isPlaying) return;

    //     const intervalMs = 1000 

    //     if (!armBot.isActive && armBot.state == "idle" && (currentPhase == "rest" || currentPhase == "init") && !isIdleRef.current) {
    //         isIdleRef.current = true

    //         // Stop the timer
    //         // 🚨 1. Clear Active Timer
    //         if (activeTimerId.current) {
    //             clearInterval(activeTimerId.current);
    //             activeTimerId.current = null;
    //         }
    //         incrementActiveTime(armBot.modelUuid, activeSecondsElapsed.current)
    //         console.log(`✅ Active Cycle completed in ${activeSecondsElapsed.current} seconds`);

    //         // 🚨 2. Reset active timer seconds after logging
    //         // activeSecondsElapsed.current = 0;

    //         // 🚨 3. Start Idle Timer (clean old idle timer first)
    //         if (idleTimerId.current) {
    //             clearInterval(idleTimerId.current);
    //             idleTimerId.current = null;
    //         }

    //         idleSecondsElapsed.current = 0;
    //         idleTimerId.current = setInterval(() => {
    //             if (!isPausedRef.current) {
    //                 idleSecondsElapsed.current += 1;
    //                 console.log(`🕒 Idle Timer: ${idleSecondsElapsed.current} seconds`);
    //             }
    //         }, intervalMs);
    //     }
    //      if (armBot.isActive && armBot.state != "idle" && currentPhase !== "rest" && armBot.currentAction && isIdleRef.current) {
    //         isIdleRef.current = false

    //         if (armBot.currentAction) {
    //             // 🚨 Clear Idle Timer
    //             if (idleTimerId.current) {
    //                 clearInterval(idleTimerId.current);
    //                 idleTimerId.current = null;
    //             }
    //             incrementIdleTime(armBot.modelUuid, idleSecondsElapsed.current)
    //             console.log(`🕒 Idle Cycle completed in: ${idleSecondsElapsed.current} seconds`);
    //             idleSecondsElapsed.current = 0;

    //             // 🚨 Start Active Timer
    //             if (activeTimerId.current) {
    //                 clearInterval(activeTimerId.current);
    //             }
    //             // activeSecondsElapsed.current = 0;
    //             activeTimerId.current = setInterval(() => {
    //                 if (!isPausedRef.current) {
    //                     activeSecondsElapsed.current += 1
    //                     console.log(`🕒 Active Timer: ${activeSecondsElapsed.current} seconds`);
    //                 }
    //             }, intervalMs);
    //         }
    //     }

    // }, [armBot, currentPhase, isPlaying])