import { useEffect } from "react";
import { useActionHandler } from "../actions/useActionHandler";
import { usePlayButtonStore, useResetButtonStore } from "../../../store/ui/usePlayButtonStore";
import { determineExecutionOrder } from "./functions/determineExecutionOrder";
import { useSceneContext } from "../../scene/sceneContext";
import SimulationHandler from "./simulationHandler";
import { useParams } from "react-router-dom";
import { useSimulationManager } from "../../../store/rough/useSimulationManagerStore";
import { getSimulationDataApi } from "../../../services/simulation/comparison/getSimulationDataApi";
import { getProductApi } from "../../../services/simulation/products/getProductApi";
import { useIsComparing } from "../../../store/builder/store";

function Simulator() {
    const { productStore, versionStore } = useSceneContext();
    const { products, getProductById, selectedProduct } = productStore();
    const { handleAction } = useActionHandler();
    const { isPlaying } = usePlayButtonStore();
    const { isReset } = useResetButtonStore();
    const { projectId } = useParams();
    const { selectedVersion } = versionStore();
    const { setIsComparing } = useIsComparing();
    const { addSimulationRecords } = useSimulationManager();

    useEffect(() => {
        if (!isPlaying || isReset || !selectedProduct.productUuid) return;

        const product = getProductById(selectedProduct.productUuid);
        if (!product) return;

        const executionOrder = determineExecutionOrder([product]);

        executionOrder.forEach((action) => {
            handleAction(action);
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [products, isPlaying, isReset, selectedProduct]);

    useEffect(() => {
        if (!projectId || !selectedVersion || !selectedProduct?.productUuid) return;
        getSimulationDataApi(projectId, selectedVersion.versionId, selectedProduct?.productUuid).then((getData) => {
            getProductApi(selectedProduct.productUuid, projectId, selectedVersion.versionId).then((product) => {
                if (!product) return;
                const getSimulate = getData?.data;

                if (getData?.message !== "Simulated data not found" && getSimulate && getSimulate.productTimestamp === product?.timestamp) {
                    addSimulationRecords(projectId, selectedVersion?.versionId || "", selectedProduct?.productUuid || "", getSimulate.data);
                    echo.warn("Simulation data is up to date");
                    return;
                } else {
                    setIsComparing(false);
                    echo.warn("Please run the simulation before comparing.");
                }
            });
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedProduct, projectId]);

    return (
        <>
            <SimulationHandler />
        </>
    );
}

export default Simulator;
