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/usePlayButtonStore';
import { useSceneContext } from '../../scene/sceneContext';
import { useProductContext } from './productContext';
import { useComparisonProduct, useMainProduct } from '../../../store/simulation/useSimulationStore';
import { useParams } from 'react-router-dom';
import { useVersionContext } from '../../builder/version/versionContext';

function Products() {
    const { armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, humanStore, layout, productStore } = useSceneContext();
    const { products, getProductById, addProduct, setProducts } = productStore();
    const { selectedProductStore } = useProductContext();
    const { setMainProduct } = useMainProduct();
    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 { addHuman, addCurrentAction, clearHumans } = humanStore();
    const { isReset } = useResetButtonStore();
    const { isPlaying } = usePlayButtonStore();
    const { mainProduct } = useMainProduct();
    const { comparisonProduct } = useComparisonProduct();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { projectId } = useParams();

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

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

    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') {
                    setSelectedProduct(id, name);
                    setMainProduct(id, name);
                }
            } else {
                setProducts(data);
                if (layout === 'Main Layout') {
                    setSelectedProduct(data[0].productUuid, data[0].productName);
                    setMainProduct(data[0].productUuid, data[0].productName);
                }
            }
        }).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.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]);

    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) {
                            addCurrentAction(events.modelUuid, events.point.actions[0].actionUuid);
                        }
                    }
                });
            }
        }
    }, [selectedProduct, products, isReset, isPlaying]);

    return (
        <>

        </>
    )
}

export default Products