import * as THREE from 'three';
import { useEffect } from 'react';
import { useProductStore } from '../../../store/simulation/useProductStore';
import { upsertProductOrEventApi } from '../../../services/simulation/products/UpsertProductOrEventApi';
import { getAllProductsApi } from '../../../services/simulation/products/getallProductsApi';
import { usePlayButtonStore, useResetButtonStore } from '../../../store/usePlayButtonStore';
import { useSceneContext } from '../../scene/sceneContext';
import { useProductContext } from './productContext';
import { useComparisonProduct, useMainProduct } from '../../../store/simulation/useSimulationStore';

function Products() {
    const { armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, layout } = useSceneContext();
    const { products, getProductById, addProduct, setProducts } = useProductStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct, setSelectedProduct } = selectedProductStore();
    const { addVehicle, clearvehicles } = vehicleStore();
    const { addArmBot, clearArmBots } = armBotStore();
    const { addMachine, clearMachines } = machineStore();
    const { addConveyor, clearConveyors } = conveyorStore();
    const { setCurrentMaterials, clearStorageUnits, updateCurrentLoad, addStorageUnit } = storageUnitStore();
    const { isReset } = useResetButtonStore();
    const { isPlaying } = usePlayButtonStore();
    const { mainProduct } = useMainProduct();
    const { comparisonProduct } = useComparisonProduct();

    useEffect(() => {
        if (layout === 'Main Layout' && mainProduct) {
            setSelectedProduct(mainProduct.productId, mainProduct.productName);
        }
    }, [mainProduct])

    useEffect(() => {
        if (layout === 'Comparison Layout' && comparisonProduct) {
            setSelectedProduct(comparisonProduct.productId, comparisonProduct.productName);
        }
    }, [comparisonProduct])

    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 })
                if (layout === 'Main Layout') {
                    setSelectedProduct(id, name);
                }
            } else {
                setProducts(data);
                if (layout === 'Main Layout') {
                    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;
                            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 (
        <>

        </>
    )
}

export default Products