import * as THREE from "three";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { useContextActionStore, 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 { handleAssetPositionSnap } from "./functions/handleAssetPositionSnap";
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({ 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 { userId, organization } = getUserData();
    const { projectId } = useParams();
    const { assetStore, eventStore, productStore, undoRedo3DStore } = useSceneContext();
    const { push3D } = undoRedo3DStore();
    const { updateAsset, getAssetById, movedObjects, setMovedObjects, pastedObjects, setPastedObjects, duplicatedObjects, setDuplicatedObjects, rotatedObjects, setRotatedObjects } = assetStore();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();

    const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("");
    const [axisConstraint, setAxisConstraint] = useState<"x" | "z" | null>(null);
    const [dragOffset, setDragOffset] = useState<THREE.Vector3 | null>(null);
    const [initialPositions, setInitialPositions] = useState<Record<string, THREE.Vector3>>({});
    const [initialStates, setInitialStates] = useState<Record<string, { position: THREE.Vector3; rotation?: THREE.Euler; }>>({});
    const [isMoving, setIsMoving] = useState(false);
    const mouseButtonsDown = useRef<{ left: boolean; right: boolean }>({ left: false, right: false, });
    const { contextAction, setContextAction } = useContextActionStore()
    const fineMoveBaseRef = useRef<THREE.Vector3 | null>(null);
    const lastPointerPositionRef = useRef<THREE.Vector3 | null>(null);
    const wasShiftHeldRef = useRef(false);

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

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

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

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

        let isPointerMoving = false;

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

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

            if (keyCombination === "") {
                setKeyEvent("");
            } else if (keyCombination === "Ctrl" || keyCombination === "Ctrl+Shift" || keyCombination === "Shift") {
                setKeyEvent(keyCombination);
            }
            if (movedObjects[0]) {
                const intersectionPoint = new THREE.Vector3();
                raycaster.setFromCamera(pointer, camera);
                const hit = raycaster.ray.intersectPlane(plane, intersectionPoint);
                if (hit) {
                    const newOffset = calculateDragOffset(movedObjects[0], intersectionPoint);
                    setDragOffset(newOffset);
                }
            }
        };

        const onPointerDown = (event: PointerEvent) => {
            isPointerMoving = false;

            if (event.button === 0) mouseButtonsDown.current.left = true;
            if (event.button === 2) mouseButtonsDown.current.right = true;
        };

        const onPointerUp = (event: PointerEvent) => {
            if (event.button === 0) mouseButtonsDown.current.left = false;
            if (event.button === 2) mouseButtonsDown.current.right = false;

            if (!isPointerMoving && movedObjects.length > 0 && event.button === 0) {
                event.preventDefault();
                placeMovedAssets();
            }
            if (!isPointerMoving && movedObjects.length > 0 && event.button === 2) {
                event.preventDefault();
                resetToInitialPositions();
                clearSelection();
                setMovedObjects([]);
            }
        };

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

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

            if (isMoving && movedObjects.length > 0) {
                if (event.key.toLowerCase() === 'x') {
                    setAxisConstraint(prev => prev === 'x' ? null : 'x');
                    event.preventDefault();
                    return;
                }
                if (event.key.toLowerCase() === 'z') {
                    setAxisConstraint(prev => prev === 'z' ? null : 'z');
                    event.preventDefault();
                    return;
                }
            }

            if (keyCombination !== keyEvent) {
                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();
                resetToInitialPositions();
                clearSelection();
                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, initialStates]);

    const calculateDragOffset = useCallback((point: THREE.Object3D, hitPoint: THREE.Vector3) => {
        const pointPosition = new THREE.Vector3().copy(point.position);
        return new THREE.Vector3().subVectors(pointPosition, hitPoint);
    }, []);

    const resetToInitialPositions = useCallback(() => {
        setTimeout(() => {
            movedObjects.forEach((movedObject: THREE.Object3D) => {
                if (movedObject.userData.modelUuid && initialStates[movedObject.uuid]) {
                    const initialState = initialStates[movedObject.uuid];
                    const positionArray: [number, number, number] = [
                        initialState.position.x,
                        initialState.position.y,
                        initialState.position.z
                    ];

                    updateAsset(movedObject.userData.modelUuid, {
                        position: positionArray,
                        rotation: [
                            initialState.rotation?.x || 0,
                            initialState.rotation?.y || 0,
                            initialState.rotation?.z || 0
                        ],
                    });

                    movedObject.position.copy(initialState.position);
                    if (initialState.rotation) {
                        movedObject.rotation.copy(initialState.rotation);
                    }
                }
            });
            setAxisConstraint(null);
        }, 50)
    }, [movedObjects, initialStates, updateAsset]);

    useEffect(() => {
        if (movedObjects.length > 0) {
            const intersectionPoint = new THREE.Vector3();
            raycaster.setFromCamera(pointer, camera);
            const hit = raycaster.ray.intersectPlane(plane, intersectionPoint);
            if (hit) {
                const newOffset = calculateDragOffset(movedObjects[0], intersectionPoint);
                setDragOffset(newOffset);
            }
        }
    }, [axisConstraint, camera, movedObjects])

    useFrame(() => {
        if (!isMoving || movedObjects.length === 0) return;

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

        if (hit) {
            if (mouseButtonsDown.current.left || mouseButtonsDown.current.right) {
                if (movedObjects[0]) {
                    const newOffset = calculateDragOffset(movedObjects[0], intersectionPoint);
                    setDragOffset(newOffset);
                }
                return;
            }

            if (dragOffset) {
                const rawBasePosition = new THREE.Vector3().addVectors(intersectionPoint, dragOffset);
                const model = movedObjects[0];
                const baseNewPosition = handleAssetPositionSnap({ rawBasePosition, intersectionPoint, model, axisConstraint, keyEvent, fineMoveBaseRef, lastPointerPositionRef, wasShiftHeldRef });

                movedObjects.forEach((movedAsset: THREE.Object3D) => {
                    if (movedAsset.userData.modelUuid) {
                        const initialPosition = initialPositions[movedAsset.userData.modelUuid];

                        if (initialPosition) {
                            const relativeOffset = new THREE.Vector3().subVectors(
                                initialPosition,
                                initialPositions[movedObjects[0].uuid]
                            );
                            const model = scene.getObjectByProperty("uuid", movedAsset.userData.modelUuid);

                            const newPosition = new THREE.Vector3().addVectors(baseNewPosition, relativeOffset);
                            const positionArray: [number, number, number] = [newPosition.x, newPosition.y, newPosition.z];

                            if (model) {
                                model.position.set(...positionArray);
                            }
                        }
                    }
                });

                const position = new THREE.Vector3();
                if (boundingBoxRef.current) {
                    boundingBoxRef.current.getWorldPosition(position);
                } else {
                    const box = new THREE.Box3();
                    movedObjects.forEach((obj: THREE.Object3D) => box.expandByObject(obj));
                    const center = new THREE.Vector3();
                    box.getCenter(center);
                }
            }
        }
    });

    const moveAssets = () => {
        const states: Record<string, { position: THREE.Vector3; rotation?: THREE.Euler; }> = {};
        const positions: Record<string, THREE.Vector3> = {};

        selectedAssets.forEach((asset: THREE.Object3D) => {
            states[asset.uuid] = {
                position: new THREE.Vector3().copy(asset.position),
                rotation: asset.rotation ? new THREE.Euler().copy(asset.rotation) : undefined
            };
            positions[asset.uuid] = new THREE.Vector3().copy(asset.position);
        });

        setInitialStates(states);
        setInitialPositions(positions);

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

        if (hit && selectedAssets[0]) {
            const offset = calculateDragOffset(selectedAssets[0], hit);
            setDragOffset(offset);
        }

        setMovedObjects(selectedAssets);
        setIsMoving(true);
    };

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

        const undoActions: UndoRedo3DAction[] = [];
        const assetsToUpdate: AssetData[] = [];

        movedObjects.forEach(async (movedAsset: THREE.Object3D) => {
            if (movedAsset) {
                const assetUuid = movedAsset.userData.modelUuid;
                const asset = getAssetById(assetUuid);
                const model = scene.getObjectByProperty("uuid", movedAsset.userData.modelUuid);
                if (!asset || !model) return;
                const position = new THREE.Vector3().copy(model.position);
                const initialState = initialStates[movedAsset.uuid];

                if (initialState) {
                    assetsToUpdate.push({
                        type: "Asset",
                        assetData: {
                            ...asset,
                            position: [
                                initialState.position.x,
                                initialState.position.y,
                                initialState.position.z
                            ],
                            rotation: [
                                initialState.rotation?.x || 0,
                                initialState.rotation?.y || 0,
                                initialState.rotation?.z || 0
                            ]
                        },
                        newData: {
                            ...asset,
                            position: [position.x, position.y, position.z],
                            rotation: [movedAsset.rotation.x, movedAsset.rotation.y, movedAsset.rotation.z]
                        },
                        timeStap: new Date().toISOString()
                    });
                }

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

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

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

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

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

                        newFloorItem.eventData = eventData;
                    }
                }

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

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

                //REST

                // await setAssetsApi(data);

                //SOCKET

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

        if (assetsToUpdate.length > 0) {
            if (assetsToUpdate.length === 1) {
                undoActions.push({
                    module: "builder",
                    actionType: "Asset-Update",
                    asset: assetsToUpdate[0]
                });
            } else {
                undoActions.push({
                    module: "builder",
                    actionType: "Assets-Update",
                    assets: assetsToUpdate
                });
            }

            push3D({
                type: 'Scene',
                actions: undoActions
            });
        }

        echo.success("Object moved!");
        setIsMoving(false);
        clearSelection();
        setAxisConstraint(null);
    };

    const clearSelection = () => {
        setPastedObjects([]);
        setDuplicatedObjects([]);
        setMovedObjects([]);
        setRotatedObjects([]);
        setSelectedAssets([]);
        setKeyEvent("");
    };

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

export default MoveControls3D;