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 {
    getSimulationData,
    saveSimulationData,
} from "../../../components/layout/scenes/functions/simulationStorage";
import { useSimulationManager } from "../../../store/rough/useSimulationManagerStore";
import { useSimulateId } 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 { setSimulateId } = useSimulateId();
    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);
        });
    }, [products, isPlaying, isReset, selectedProduct]);

    useEffect(() => {
        if (!projectId || !selectedVersion || !selectedProduct?.productUuid) return;
        const fetchSimulateData = async () => {
            const getData = await getSimulationData(
                projectId,
                selectedVersion.versionId,
                selectedProduct?.productUuid
            );
            const product = getProductById(selectedProduct.productUuid);
            if (!product) return;
            const products: ProductsSchema = [product];
            const getSimulate = getData?.data;
            // console.log("getSimulate: ", getSimulate);
            if (getData && getSimulate && getSimulate.productTimestamp === products[0]?.timestamp) {
                setSimulateId(getSimulate._id);
                // console.log(" getSimulate.data: ", getSimulate.data);
                addSimulationRecords(
                    projectId,
                    selectedVersion?.versionId || "",
                    selectedProduct?.productUuid || "",
                    getSimulate.data // ✅ this is already an array
                );
                echo.log("Simulation data is up to date");
                return;
            } else {
                //call create API
                const data = {
                    projectId: projectId,
                    versionId: selectedVersion.versionId,
                    productUuid: selectedProduct.productUuid,
                    simulateData: useSimulationManager
                        .getState()
                        .getProductById(
                            projectId,
                            selectedVersion?.versionId,
                            selectedProduct.productUuid
                        )?.simulateData,
                };
                const simulations = await saveSimulationData(data);
                // console.log("simulations: ", simulations);
                echo.log("Simulation data saved successfully");
            }
        };
        fetchSimulateData();
    }, []);

    return (
        <>
            {/* <simulationHandler/> */}
            <SimulationHandler />
        </>
    );
}

export default Simulator;
