import * as THREE from "three";
import { useEffect, useMemo, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { useSelectedAssets, useSocketStore, useToggleView, } from "../../../../../store/builder/store";
import * as Types from "../../../../../types/world/worldTypes";
import { detectModifierKeys } from "../../../../../utils/shortcutkeys/detectModifierKeys";
import { upsertProductOrEventApi } from "../../../../../services/simulation/products/UpsertProductOrEventApi";
import { snapControls } from "../../../../../utils/handleSnap";
import DistanceFindingControls from "./distanceFindingControls";
import { useParams } from "react-router-dom";
import { useProductContext } from "../../../../simulation/products/productContext";
import { getUserData } from "../../../../../functions/getUserData";
import { useSceneContext } from "../../../sceneContext";
import { useVersionContext } from "../../../../builder/version/versionContext";

// import { setAssetsApi } from '../../../../../services/factoryBuilder/asset/floorAsset/setAssetsApi';

function MoveControls3D({
    movedObjects,
    setMovedObjects,
    pastedObjects,
    setpastedObjects,
    duplicatedObjects,
    setDuplicatedObjects,
    selectionGroup,
    rotatedObjects,
    setRotatedObjects,
    boundingBoxRef,
}: any) {
    const { camera, controls, gl, scene, pointer, raycaster } = useThree();
    const plane = useMemo(() => new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), []);

    const { toggleView } = useToggleView();
    const { selectedAssets, setSelectedAssets } = useSelectedAssets();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { socket } = useSocketStore();
    const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("");
    const { userId, organization } = getUserData();
    const { projectId } = useParams();
    const { assetStore, eventStore, productStore } = useSceneContext();
    const { updateAsset } = assetStore();
    const AssetGroup = useRef<THREE.Group | undefined>(undefined);
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();

    const updateBackend = (
        productName: string,
        productUuid: string,
        projectId: string,
        eventData: EventsSchema
    ) => {
        upsertProductOrEventApi({
            productName: productName,
            productUuid: productUuid,
            projectId: projectId,
            eventDatas: eventData,
            versionId: selectedVersion?.versionId || '',
        });
    };

    useEffect(() => {
        if (!camera || !scene || toggleView) return;

        const canvasElement = gl.domElement;
        canvasElement.tabIndex = 0;

        const itemsGroup: any = scene.getObjectByName("Asset Group");
        AssetGroup.current = itemsGroup;

        if (!AssetGroup.current) {
            console.error("Asset Group not found in the scene.");
            return;
        }

        let isMoving = false;

        const onPointerDown = () => {
            isMoving = false;
        };

        const onPointerMove = () => {
            isMoving = true;
        };

        const onKeyUp = (event: KeyboardEvent) => {
            const isModifierKey = event.key === "Control" || event.key === "Shift";

            if (isModifierKey) {
                setKeyEvent("");
            }
        };

        const onPointerUp = (event: PointerEvent) => {
            if (!isMoving && movedObjects.length > 0 && event.button === 0) {
                event.preventDefault();
                placeMovedAssets();
            }
            if (!isMoving && movedObjects.length > 0 && event.button === 2) {
                event.preventDefault();

                clearSelection();
                movedObjects.forEach((asset: any) => {
                    if (AssetGroup.current) {
                        AssetGroup.current.attach(asset);
                    }
                });

                setMovedObjects([]);
            }
            setKeyEvent("");
        };

        const onKeyDown = (event: KeyboardEvent) => {
            const keyCombination = detectModifierKeys(event);

            if (pastedObjects.length > 0 || duplicatedObjects.length > 0 || rotatedObjects.length > 0)
                return;

            if (keyCombination === "Ctrl" || keyCombination === "Ctrl+Shift" || keyCombination === "Shift") {
                setKeyEvent(keyCombination);
            } else {
                setKeyEvent("");
            }

            if (keyCombination === "G") {
                if (selectedAssets.length > 0) {
                    moveAssets();
                }
            }

            if (keyCombination === "ESCAPE") {
                event.preventDefault();

                clearSelection();
                movedObjects.forEach((asset: any) => {
                    if (AssetGroup.current) {
                        AssetGroup.current.attach(asset);
                    }
                });

                setMovedObjects([]);
            }
        };

        if (!toggleView) {
            canvasElement.addEventListener("pointerdown", onPointerDown);
            canvasElement.addEventListener("pointermove", onPointerMove);
            canvasElement.addEventListener("pointerup", onPointerUp);
            canvasElement.addEventListener("keydown", onKeyDown);
            canvasElement?.addEventListener("keyup", onKeyUp);
        }

        return () => {
            canvasElement.removeEventListener("pointerdown", onPointerDown);
            canvasElement.removeEventListener("pointermove", onPointerMove);
            canvasElement.removeEventListener("pointerup", onPointerUp);
            canvasElement.removeEventListener("keydown", onKeyDown);
            canvasElement?.removeEventListener("keyup", onKeyUp);
        };
    }, [camera, controls, scene, toggleView, selectedAssets, socket, pastedObjects, duplicatedObjects, movedObjects, rotatedObjects, keyEvent,]);

    let moveSpeed = keyEvent === "Ctrl" || "Ctrl+Shift" ? 1 : 0.25;

    useFrame(() => {
        if (movedObjects.length > 0) {
            const intersectionPoint = new THREE.Vector3();
            raycaster.setFromCamera(pointer, camera);
            let point = raycaster.ray.intersectPlane(plane, intersectionPoint);
            const floorsGroup = scene.getObjectByName("Floors-Group") as Types.Group | null;
            const floorChildren = floorsGroup?.children ?? [];
            const floorIntersections = raycaster.intersectObjects([...floorChildren], true);
            const intersectedFloor = floorIntersections.find((intersect) => intersect.object.name.includes("Floor"));

            if (intersectedFloor && selectedAssets.length === 1) {
                if (intersectedFloor.object.userData.floorUuid) {
                    point = new THREE.Vector3(intersectedFloor.point.x, intersectedFloor.object.userData.floorDepth, intersectedFloor.point.z);
                }
            }

            if (point) {
                let targetX = point.x;
                let targetY = point.y;
                let targetZ = point.z;

                if (keyEvent === "Ctrl") {
                    targetX = snapControls(targetX, "Ctrl");
                    targetZ = snapControls(targetZ, "Ctrl");
                }

                // else if (keyEvent === "Ctrl+Shift") {
                //     targetX = snapControls(targetX, "Ctrl+Shift");
                //     targetZ = snapControls(targetZ, "Ctrl+Shift");
                // } else if (keyEvent === "Shift") {
                //     targetX = snapControls(targetX, "Shift");
                //     targetZ = snapControls(targetZ, "Shift");
                // } else {
                // }

                const position = new THREE.Vector3();

                if (boundingBoxRef.current) {
                    boundingBoxRef.current.getWorldPosition(position);
                    selectionGroup.current.position.lerp(
                        new THREE.Vector3(
                            targetX - (position.x - selectionGroup.current.position.x),
                            targetY - (position.y - selectionGroup.current.position.y),
                            targetZ - (position.z - selectionGroup.current.position.z)
                        ),
                        moveSpeed
                    );
                } else {
                    const box = new THREE.Box3();
                    movedObjects.forEach((obj: THREE.Object3D) =>
                        box.expandByObject(obj)
                    );
                    const center = new THREE.Vector3();
                    box.getCenter(center);

                    selectionGroup.current.position.lerp(
                        new THREE.Vector3(
                            targetX - (center.x - selectionGroup.current.position.x),
                            selectionGroup.current.position.y,
                            targetZ - (center.z - selectionGroup.current.position.z)
                        ),
                        moveSpeed
                    );
                }
            }
        }
    });

    const moveAssets = () => {
        setMovedObjects(selectedAssets);
        selectedAssets.forEach((asset: any) => {
            selectionGroup.current.attach(asset);
        });
    };

    const placeMovedAssets = () => {
        if (movedObjects.length === 0) return;

        movedObjects.forEach(async (obj: THREE.Object3D) => {
            if (obj && AssetGroup.current) {
                let worldPosition = new THREE.Vector3();
                obj.getWorldPosition(worldPosition);

                if (worldPosition.y < 0) {
                    worldPosition.y = 0;
                }

                selectionGroup.current.remove(obj);
                obj.position.copy(worldPosition);

                const newFloorItem: Types.FloorItemType = {
                    modelUuid: obj.userData.modelUuid,
                    modelName: obj.userData.modelName,
                    assetId: obj.userData.assetId,
                    position: [worldPosition.x, worldPosition.y, worldPosition.z],
                    rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
                    isLocked: false,
                    isVisible: true,
                };

                if (obj.userData.eventData) {
                    const eventData = eventStore.getState().getEventByModelUuid(obj.userData.modelUuid);
                    const productData = productStore.getState().getEventByModelUuid(selectedProduct.productUuid, obj.userData.modelUuid);

                    if (eventData) {
                        eventStore.getState().updateEvent(obj.userData.modelUuid, {
                            position: [worldPosition.x, worldPosition.y, worldPosition.z],
                            rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
                        });
                    }

                    if (productData) {
                        const event = productStore
                            .getState()
                            .updateEvent(
                                selectedProduct.productUuid,
                                obj.userData.modelUuid,
                                {
                                    position: [worldPosition.x, worldPosition.y, worldPosition.z],
                                    rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
                                }
                            );

                        if (event) {
                            updateBackend(
                                selectedProduct.productName,
                                selectedProduct.productUuid,
                                projectId || '',
                                event
                            );
                        }

                        newFloorItem.eventData = eventData;
                    }
                }

                updateAsset(obj.userData.modelUuid, {
                    position: [worldPosition.x, worldPosition.y, worldPosition.z],
                    rotation: [obj.rotation.x, obj.rotation.y, obj.rotation.z],
                });

                //REST

                // await setAssetsApi(
                //     organization,
                //     obj.uuid,
                //     obj.userData.name,
                //     [worldPosition.x, worldPosition.y, worldPosition.z],
                //     { "x": obj.rotation.x, "y": obj.rotation.y, "z": obj.rotation.z },
                //     obj.userData.modelId,
                //     false,
                //     true,
                // );

                //SOCKET

                const data = {
                    organization,
                    modelUuid: newFloorItem.modelUuid,
                    modelName: newFloorItem.modelName,
                    assetId: newFloorItem.assetId,
                    position: newFloorItem.position,
                    rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
                    isLocked: false,
                    isVisible: true,
                    socketId: socket.id,
                    versionId: selectedVersion?.versionId || '',
                    projectId,
                    userId
                };

                // console.log('data: ', data);
                socket.emit("v1:model-asset:add", data);

                AssetGroup.current.add(obj);
            }
        });

        echo.success("Object moved!");

        clearSelection();
    };

    const clearSelection = () => {
        selectionGroup.current.children = [];
        selectionGroup.current.position.set(0, 0, 0);
        selectionGroup.current.rotation.set(0, 0, 0);
        setpastedObjects([]);
        setDuplicatedObjects([]);
        setMovedObjects([]);
        setRotatedObjects([]);
        setSelectedAssets([]);
        setKeyEvent("");
    };

    return (
        <DistanceFindingControls
            boundingBoxRef={boundingBoxRef}
            object={movedObjects.length}
        />
    );
}

export default MoveControls3D;
