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 ZoneCreator from './zoneCreator/zoneCreator';
import ZoneInstances from './Instances/zoneInstances';

import { getZonesApi } from '../../../services/factoryBuilder/zone/getZonesApi';

function ZoneGroup() {
    const { togglView } = useToggleView();
    const { setSelectedZone } = useBuilderStore();
    const { activeModule } = useModuleStore();
    const { activeTool } = useActiveTool();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { zoneStore } = useSceneContext();
    const { setZones } = zoneStore();
    const { projectId } = useParams();

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

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

    return (
        <>

            <ZoneCreator />

            <ZoneInstances />

        </>
    )
}

export default ZoneGroup