import * as THREE from 'three';
import { useEffect } from 'react';
import { useProductStore } from '../../../store/simulation/useProductStore';
import { useSelectedProduct } from '../../../store/simulation/useSimulationStore';
import AddOrRemoveEventsInProducts from './events/addOrRemoveEventsInProducts';
import { upsertProductOrEventApi } from '../../../services/simulation/products/UpsertProductOrEventApi';
import { getAllProductsApi } from '../../../services/simulation/products/getallProductsApi';
import { useVehicleStore } from '../../../store/simulation/useVehicleStore';
import { useArmBotStore } from '../../../store/simulation/useArmBotStore';
import { useConveyorStore } from '../../../store/simulation/useConveyorStore';
import { useMachineStore } from '../../../store/simulation/useMachineStore';
import { useStorageUnitStore } from '../../../store/simulation/useStorageUnitStore';
import { usePlayButtonStore, useResetButtonStore } from '../../../store/usePlayButtonStore';

function Products() {
    const { products, getProductById, addProduct, setProducts } = useProductStore();
    const { selectedProduct, setSelectedProduct } = useSelectedProduct();
    const { addVehicle, clearvehicles } = useVehicleStore();
    const { addArmBot, clearArmBots } = useArmBotStore();
    const { addMachine, clearMachines } = useMachineStore();
    const { addConveyor, clearConveyors } = useConveyorStore();
    const { setCurrentMaterials, clearStorageUnits, updateCurrentLoad, addStorageUnit } = useStorageUnitStore();
    const { isReset } = useResetButtonStore();
    const { isPlaying } = usePlayButtonStore();

    useEffect(() => {
        const email = localStorage.getItem('email')
        const organization = (email!.split("@")[1]).split(".")[0];
        getAllProductsApi(organization).then((data) => {
            if (data.length === 0) {
                const id = THREE.MathUtils.generateUUID();
                const name = 'Product 1';
                addProduct(name, id);
                upsertProductOrEventApi({ productName: name, productId: id, organization: organization })
                setSelectedProduct(id, name);
            } else {
                setProducts(data);
                setSelectedProduct(data[0].productId, data[0].productName);
            }
        })
    }, [])

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

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

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

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

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

                        if (event.point.action.actionType === 'retrieve') {
                            const storageAction = event.point.action as StorageAction;
                            const materials = Array.from({ length: storageAction.storageCapacity }, () => ({
                                materialType: storageAction.materialType || 'Default material',
                                materialId: THREE.MathUtils.generateUUID()
                            }));

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

    return (
        <>

            <AddOrRemoveEventsInProducts />

        </>
    )
}

export default Products