import { useEffect } from 'react';
import { useToggleView, useToolMode } from '../../../store/builder/store';
import { useBuilderStore } from '../../../store/builder/useBuilderStore';
import { useVersionContext } from '../version/versionContext';
import { useSceneContext } from '../../scene/sceneContext';
import { useParams } from 'react-router-dom';
import useModuleStore from '../../../store/useModuleStore';
import WallAssetCreator from './wallAssetCreator'
import WallAssetInstances from './Instances/wallAssetInstances'
import { getWallAssetsApi } from '../../../services/factoryBuilder/asset/wallAsset/getWallAssetsApi';

function WallAssetGroup() {
    const { toggleView } = useToggleView();
    const { setSelectedWallAsset, setDeletableWallAsset } = useBuilderStore();
    const { activeModule } = useModuleStore();
    const { toolMode } = useToolMode();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { wallAssetStore } = useSceneContext();
    const { setWallAssets } = wallAssetStore();
    const { projectId } = useParams();

    useEffect(() => {
        if (toggleView || activeModule !== 'builder' || toolMode !== 'cursor') {
            setSelectedWallAsset(null);
        }
        setDeletableWallAsset(null);
    }, [toggleView, activeModule, toolMode])

    useEffect(() => {
        if (projectId && selectedVersion) {
            getWallAssetsApi(projectId, selectedVersion?.versionId || '').then((wallAssets) => {
                if (wallAssets && wallAssets.length > 0) {
                    setWallAssets(wallAssets);
                } else {
                    setWallAssets([]);
                }
            }).catch((err) => {
                console.log(err);
            })
        }
    }, [projectId, selectedVersion?.versionId])

    return (
        <>

            <WallAssetCreator />

            <WallAssetInstances />

        </>
    )
}

export default WallAssetGroup