import * as THREE from "three";
import { useEffect } from "react";
import { upsertProductOrEventApi } from "../../../services/simulation/products/UpsertProductOrEventApi";
import { getAllProductsApi } from "../../../services/simulation/products/getallProductsApi";
import { usePlayButtonStore, useResetButtonStore } from "../../../store/ui/usePlayButtonStore";
import { useSceneContext } from "../../scene/sceneContext";
import { useSimulationState } from "../../../store/simulation/useSimulationStore";
import { useParams } from "react-router-dom";

function Products() {
    const { armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, humanStore, craneStore, layout, productStore, versionStore } = useSceneContext();
    const { products, getProductById, addProduct, setProducts, selectedProduct, setSelectedProduct } = productStore();
    const { addVehicle, clearVehicles } = vehicleStore();
    const { addArmBot, clearArmBots } = armBotStore();
    const { addMachine, clearMachines } = machineStore();
    const { addConveyor, clearConveyors } = conveyorStore();
    const { setCurrentMaterials, clearStorageUnits, updateCurrentLoad, addStorageUnit } = storageUnitStore();
    const { addHuman, addCurrentAction: addCurrentActionHuman, clearHumans } = humanStore();
    const { addCrane, addCurrentAction: addCurrentActionCrane, clearCranes } = craneStore();
    const { isReset } = useResetButtonStore();
    const { isPlaying } = usePlayButtonStore();
    const { setMainState, mainScene, comparisonScene } = useSimulationState();
    const { selectedVersion } = versionStore();
    const { projectId } = useParams();

    useEffect(() => {
        if (layout === "Main Layout" && mainScene) {
            setSelectedProduct(mainScene.product.productUuid, mainScene.product.productName);
        }
    }, [mainScene, layout]);

    useEffect(() => {
        if (layout === "Comparison Layout" && comparisonScene) {
            setSelectedProduct(comparisonScene.product.productUuid, comparisonScene.product.productName);
        }
    }, [comparisonScene, layout]);

    useEffect(() => {
        if (!selectedVersion) return;
        getAllProductsApi(projectId || "", selectedVersion.versionId)
            .then((data) => {
                if (data && data.length === 0) {
                    const id = THREE.MathUtils.generateUUID();
                    const name = "Product 1";
                    addProduct(name, id);
                    upsertProductOrEventApi({
                        productName: name,
                        productUuid: id,
                        projectId: projectId || "",
                        versionId: selectedVersion.versionId,
                    });
                    if (layout === "Main Layout" && selectedVersion) {
                        setSelectedProduct(id, name);
                        const mainData = {
                            productUuid: id,
                            productName: name,
                            versionUuid: selectedVersion.versionId,
                            versionName: selectedVersion.versionName,
                        };
                        setMainState(mainData);
                    }
                } else {
                    setProducts(data);
                    if (layout === "Main Layout") {
                        setSelectedProduct(data[0].productUuid, data[0].productName);
                        const mainData = {
                            productUuid: data[0].productUuid,
                            productName: data[0].productName,
                            versionUuid: selectedVersion.versionId,
                            versionName: selectedVersion.versionName,
                        };
                        setMainState(mainData);
                    }
                }
            })
            .catch((err) => {
                console.error(err);
            });
    }, [selectedVersion?.versionId]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearVehicles();
                product.eventDatas.forEach((events) => {
                    if (events.type === "vehicle") {
                        addVehicle(selectedProduct.productUuid, events);
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearArmBots();
                product.eventDatas.forEach((events) => {
                    if (events.type === "roboticArm") {
                        addArmBot(selectedProduct.productUuid, events);
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearConveyors();
                product.eventDatas.forEach((events) => {
                    if (events.type === "transfer") {
                        addConveyor(selectedProduct.productUuid, events);
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearMachines();
                product.eventDatas.forEach((events) => {
                    if (events.type === "machine") {
                        addMachine(selectedProduct.productUuid, events);
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearStorageUnits();
                product.eventDatas.forEach((event) => {
                    if (event.type === "storageUnit") {
                        addStorageUnit(selectedProduct.productUuid, event);

                        if (event.storageCount > 0) {
                            const materials = Array.from({ length: event.storageCount }, () => ({
                                materialType: event.materialType || "Default material",
                                materialId: THREE.MathUtils.generateUUID(),
                            }));

                            setCurrentMaterials(event.modelUuid, materials);
                            updateCurrentLoad(event.modelUuid, event.storageCount);
                        } else {
                            setCurrentMaterials(event.modelUuid, []);
                            updateCurrentLoad(event.modelUuid, 0);
                        }
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearHumans();
                product.eventDatas.forEach((events) => {
                    if (events.type === "human") {
                        addHuman(selectedProduct.productUuid, events);

                        if (events.point.actions.length > 0) {
                            addCurrentActionHuman(events.modelUuid, events.point.actions[0].actionUuid);
                        }
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    useEffect(() => {
        if (selectedProduct.productUuid) {
            const product = getProductById(selectedProduct.productUuid);
            if (product) {
                clearCranes();
                product.eventDatas.forEach((events) => {
                    if (events.type === "crane") {
                        addCrane(selectedProduct.productUuid, events);

                        if (events.point.actions.length > 0) {
                            addCurrentActionCrane(events.modelUuid, events.point.actions[0].actionUuid, null, null);
                        }
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    return <></>;
}

export default Products;
