import * as THREE from "three";
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useSceneContext } from "../../sceneContext";
import { useSocketStore } from "../../../../store/socket/useSocketStore";
import { useContextActionStore } from "../../../../store/builder/store";
import { getUserData } from "../../../../functions/getUserData";
import useAssetResponseHandler from "../../../collaboration/responseHandler/useAssetResponseHandler";
import useCallBackOnKey from "../../../../utils/hooks/useCallBackOnKey";

import generateUniqueAssetGroupName from "../../../builder/asset/functions/generateUniqueAssetGroupName";
import { setAssetsApi } from "../../../../services/factoryBuilder/asset/floorAsset/setAssetsApi";
import { getAssetGroupsApi } from "../../../../services/factoryBuilder/group/assetGroup/getAssetGroupsApi";
import { createAssetGroupApi } from "../../../../services/factoryBuilder/group/assetGroup/createAssetGroupApi";

function GroupControls() {
    const { projectId } = useParams();
    const { builderSocket } = useSocketStore();
    const { assetStore, undoRedo3DStore, versionStore, assetGroupStore } = useSceneContext();
    const { assetGroups, addGroup, setGroups, buildHierarchy } = assetGroupStore();
    const { push3D } = undoRedo3DStore();
    const { assets, selectedAssets, pastedObjects, duplicatedObjects, movedObjects, rotatedObjects, getSelectedAssetUuids } = assetStore();
    const { updateAssetInScene, removeAssetFromScene } = useAssetResponseHandler();
    const { contextAction, setContextAction } = useContextActionStore();
    const { selectedVersion } = versionStore();
    const { userId, organization } = getUserData();

    useEffect(() => {
        if (!projectId || !selectedVersion) return;

        // getAssetGroupsApi(projectId, selectedVersion.versionId).then((data) => {
        //     if (data && data.length > 0) {
        //         setGroups(data);
        //     }
        // });
    }, [projectId, selectedVersion]);

    useEffect(() => {
        const hierarchy = buildHierarchy(assets, assetGroups);
        // console.log("assetGroups: ", assetGroups);
        // console.log("hierarchy: ", hierarchy);
    }, [assetGroups, assets]);

    useEffect(() => {
        if (contextAction === "groupAsset") {
            setContextAction(null);
            groupSelection();
        }
    }, [contextAction, projectId, selectedVersion]);

    const groupSelection = () => {
        const assetUuids: string[] = getSelectedAssetUuids();

        if (assetUuids.length > 0 && projectId && selectedVersion) {
            const groupName = generateUniqueAssetGroupName({ baseName: "Group", existingGroups: assetGroups });

            const assetGroup: AssetGroup = {
                groupName,
                groupUuid: THREE.MathUtils.generateUUID(),
                isVisible: true,
                isLocked: false,
                isExpanded: true,
                children: assetUuids.map((assetUuid) => {
                    return { type: "Asset", childrenUuid: assetUuid };
                }),
            };

            // createAssetGroupApi({
            //     projectId,
            //     versionId: selectedVersion.versionId,
            //     groupUuid: assetGroup.groupUuid,
            //     groupName: assetGroup.groupName,
            //     isVisible: assetGroup.isVisible,
            //     isExpanded: assetGroup.isExpanded,
            //     isLocked: assetGroup.isLocked,
            //     children: assetGroup.children,
            // }).then((data) => {
            //     console.log("data: ", data);
            // });
            addGroup(assetGroup);
        }
    };

    useCallBackOnKey(
        () => {
            if (selectedAssets.length > 0 && pastedObjects.length === 0 && duplicatedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) {
                groupSelection();
            }
        },
        "Ctrl+G",
        { dependencies: [pastedObjects, duplicatedObjects, movedObjects, rotatedObjects, selectedAssets, selectedVersion, builderSocket, projectId, userId, organization], noRepeat: true }
    );

    useCallBackOnKey(() => {}, "Alt+G", { dependencies: [], noRepeat: true });

    return null;
}

export default GroupControls;
