import { useEffect } from "react";
import { useActiveTool, useToggleView } from "../../../store/builder/store";
import { useBuilderStore } from "../../../store/builder/useBuilderStore";
import { useSceneContext } from "../../scene/sceneContext";
import { useParams } from "react-router-dom";
import useModuleStore from "../../../store/ui/useModuleStore";
import ZoneCreator from "./zoneCreator/zoneCreator";
import ZoneInstances from "./Instances/zoneInstances";

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

function ZoneGroup() {
    const { toggleView } = useToggleView();
    const { setSelectedZone } = useBuilderStore();
    const { activeModule } = useModuleStore();
    const { activeTool } = useActiveTool();
    const { zoneStore, versionStore } = useSceneContext();
    const { selectedVersion } = versionStore();
    const { setZones } = zoneStore();
    const { projectId } = useParams();

    useEffect(() => {
        if (toggleView || activeModule !== "builder") {
            setSelectedZone(null);
        }
    }, [toggleView, 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;
