import { useEffect } from 'react';
import { useActiveTool, useToggleView } 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 WallCreator from './wallCreator/wallCreator';
import WallInstances from './Instances/wallInstances';

import { getWallsApi } from '../../../services/factoryBuilder/wall/getWallsApi';

function WallGroup() {
    const { togglView } = useToggleView();
    const { setSelectedWall, setSelectedDecal } = useBuilderStore();
    const { activeModule } = useModuleStore();
    const { activeTool } = useActiveTool();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { wallStore } = useSceneContext();
    const { setWalls } = wallStore();
    const { projectId } = useParams();

    useEffect(() => {
        if (togglView || activeModule !== 'builder') {
            setSelectedWall(null);
            setSelectedDecal(null);
        }
    }, [togglView, activeModule, activeTool])

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

    return (
        <>

            <WallCreator />

            <WallInstances />

        </>
    )
}

export default WallGroup