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";

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

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

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

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

        selectedAssets.forEach((selectedAsset) => {
            if (selectedAsset.userData.modelUuid) {
                assetUuids.push(selectedAsset.userData.modelUuid);
            }
        });

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

            const assetGroup: AssetGroup = {
                groupName,
                groupUuid: THREE.MathUtils.generateUUID(),
                isVisible: true,
                isLocked: false,
                isExpanded: true,
                childrens: assetUuids.map((assetUuid) => {
                    return { type: "Asset", childrenUuid: assetUuid };
                }),
            };
            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 }
    );

    return null;
}

export default GroupControls;
