import * as THREE from "three";
import { useEffect, useMemo } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { useFloorItems, useSelectedAssets, useSocketStore, useToggleView } from "../../../../store/store";
import { toast } from "react-toastify";
// import { setFloorItemApi } from '../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi';
import * as Types from "../../../../types/world/worldTypes";
import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifierKeys";

const CopyPasteControls = ({ itemsGroupRef, copiedObjects, setCopiedObjects, pastedObjects, setpastedObjects, selectionGroup, setDuplicatedObjects, movedObjects, setMovedObjects, rotatedObjects, setRotatedObjects, boundingBoxRef }: any) => {
    const { camera, controls, gl, scene, pointer, raycaster } = useThree();
    const { toggleView } = useToggleView();
    const { selectedAssets, setSelectedAssets } = useSelectedAssets();
    const plane = useMemo(() => new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), []);
    const { floorItems, setFloorItems } = useFloorItems();
    const { socket } = useSocketStore()

    useEffect(() => {
        if (!camera || !scene || toggleView) return;
        const canvasElement = gl.domElement;
        canvasElement.tabIndex = 0;

        let isMoving = false;

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

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

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

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

            if (keyCombination === "Ctrl+C" && movedObjects.length === 0 && rotatedObjects.length === 0) {
                copySelection();
            }
            if (keyCombination === "Ctrl+V" && copiedObjects.length > 0 && pastedObjects.length === 0 && movedObjects.length === 0 && rotatedObjects.length === 0) {
                pasteCopiedObjects();
            }
        };

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

        return () => {
            canvasElement.removeEventListener("pointerdown", onPointerDown);
            canvasElement.removeEventListener("pointermove", onPointerMove);
            canvasElement.removeEventListener("pointerup", onPointerUp);
            canvasElement.removeEventListener("keydown", onKeyDown);
        };

    }, [camera, controls, scene, toggleView, selectedAssets, copiedObjects, pastedObjects, movedObjects, socket, floorItems, rotatedObjects]);

    useFrame(() => {
        if (pastedObjects.length > 0) {
            const intersectionPoint = new THREE.Vector3();
            raycaster.setFromCamera(pointer, camera);
            const point = raycaster.ray.intersectPlane(plane, intersectionPoint);
            if (point) {
                const position = new THREE.Vector3();
                if (boundingBoxRef.current) {
                    boundingBoxRef.current?.getWorldPosition(position)
                    selectionGroup.current.position.set(point.x - (position.x - selectionGroup.current.position.x), selectionGroup.current.position.y, point.z - (position.z - selectionGroup.current.position.z));
                } else {
                    const box = new THREE.Box3();
                    pastedObjects.forEach((obj: THREE.Object3D) => box.expandByObject(obj.clone()));
                    const center = new THREE.Vector3();
                    box.getCenter(center);
                    selectionGroup.current.position.set(point.x - (center.x - selectionGroup.current.position.x), selectionGroup.current.position.y, point.z - (center.z - selectionGroup.current.position.z));
                }
            }
        }
    });

    const copySelection = () => {
        if (selectedAssets.length > 0) {
            const newClones = selectedAssets.map((asset: any) => {
                const clone = asset.clone();
                clone.position.copy(asset.position);
                return clone;
            });
            setCopiedObjects(newClones);
            toast.info("Objects copied!");
        }
    };

    const pasteCopiedObjects = () => {
        if (copiedObjects.length > 0 && pastedObjects.length === 0) {
            const newClones = copiedObjects.map((obj: THREE.Object3D) => {
                const clone = obj.clone();
                clone.position.copy(obj.position);
                return clone;
            });
            selectionGroup.current.add(...newClones);
            setpastedObjects([...newClones]);
            setSelectedAssets([...newClones]);

            const intersectionPoint = new THREE.Vector3();
            raycaster.setFromCamera(pointer, camera);
            const point = raycaster.ray.intersectPlane(plane, intersectionPoint);

            if (point) {
                const position = new THREE.Vector3();
                if (boundingBoxRef.current) {
                    boundingBoxRef.current?.getWorldPosition(position)
                    selectionGroup.current.position.set(point.x - (position.x - selectionGroup.current.position.x), selectionGroup.current.position.y, point.z - (position.z - selectionGroup.current.position.z));
                } else {
                    const box = new THREE.Box3();
                    newClones.forEach((obj: THREE.Object3D) => box.expandByObject(obj.clone()));
                    const center = new THREE.Vector3();
                    box.getCenter(center);
                    selectionGroup.current.position.set(point.x - (center.x - selectionGroup.current.position.x), selectionGroup.current.position.y, point.z - (center.z - selectionGroup.current.position.z));
                }
            }
        }
    };

    const addPastedObjects = () => {
        if (pastedObjects.length === 0) return;
        pastedObjects.forEach(async (obj: THREE.Object3D) => {
            const worldPosition = new THREE.Vector3();
            obj.getWorldPosition(worldPosition);
            obj.position.copy(worldPosition);

            if (itemsGroupRef.current) {

                let updatedEventData = null;
                if (obj.userData.eventData) {
                    updatedEventData = JSON.parse(JSON.stringify(obj.userData.eventData));

                    updatedEventData.modelUuid = THREE.MathUtils.generateUUID();

                    if (updatedEventData.type === "Conveyor" && updatedEventData.points) {
                        updatedEventData.points = updatedEventData.points.map((point: any) => ({
                            ...point,
                            uuid: THREE.MathUtils.generateUUID()
                        }));
                    }
                    else if (updatedEventData.type === "Vehicle" && updatedEventData.point) {
                        updatedEventData.point = {
                            ...updatedEventData.point,
                            uuid: THREE.MathUtils.generateUUID()
                        };
                    }
                    else if (updatedEventData.type === "ArmBot" && updatedEventData.point) {
                        updatedEventData.point = {
                            ...updatedEventData.point,
                            uuid: THREE.MathUtils.generateUUID()
                        };
                    }
                    else if (updatedEventData.type === "StaticMachine" && updatedEventData.point) {
                        updatedEventData.point = {
                            ...updatedEventData.point,
                            uuid: THREE.MathUtils.generateUUID()
                        };
                    }
                }

                const newFloorItem: Types.FloorItemType = {
                    modelUuid: obj.uuid,
                    modelName: obj.userData.name,
                    modelfileID: obj.userData.modelId,
                    position: [worldPosition.x, worldPosition.y, worldPosition.z],
                    rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z, },
                    isLocked: false,
                    isVisible: true,
                    eventData: updatedEventData
                };

                setFloorItems((prevItems: Types.FloorItems) => {
                    const updatedItems = [...(prevItems || []), newFloorItem];
                    localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
                    return updatedItems;
                });

                const email = localStorage.getItem("email");
                const organization = email ? email.split("@")[1].split(".")[0] : "default";

                //REST

                // await setFloorItemApi(
                //     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,
                    modelfileID: newFloorItem.modelfileID,
                    position: newFloorItem.position,
                    rotation: { x: obj.rotation.x, y: obj.rotation.y, z: obj.rotation.z },
                    isLocked: false,
                    isVisible: true,
                    socketId: socket.id,
                    eventData: updatedEventData
                };

                socket.emit("v2:model-asset:add", data);

                obj.userData = {
                    name: newFloorItem.modelName,
                    modelId: newFloorItem.modelfileID,
                    modelUuid: newFloorItem.modelUuid,
                    eventData: updatedEventData
                };

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

        toast.success("Object added!");
        clearSelection();
    };

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

    return null;
};

export default CopyPasteControls;