import * as THREE from "three";
import * as Types from "../../../../../types/world/worldTypes";
import { useCallback, useEffect, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { useContextActionStore, useToggleView, useToolMode } from "../../../../../store/builder/store";
import { useSocketStore } from "../../../../../store/socket/useSocketStore";
import { upsertProductOrEventApi } from "../../../../../services/simulation/products/UpsertProductOrEventApi";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
import { useSceneContext } from "../../../sceneContext";
import { detectModifierKeys } from "../../../../../utils/shortcutkeys/detectModifierKeys";
import { handleAssetRotationSnap } from "./functions/handleAssetRotationSnap";
import useModuleStore from "../../../../../store/ui/useModuleStore";
import useAssetResponseHandler from "../../../../collaboration/responseHandler/useAssetResponseHandler";

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

function RotateControls3D() {
    const { camera, gl, scene, pointer, raycaster } = useThree();
    const { toggleView } = useToggleView();
    const { toolMode } = useToolMode();
    const { activeModule } = useModuleStore();
    const { builderSocket } = useSocketStore();
    const { userId, organization } = getUserData();
    const { projectId } = useParams();
    const { assetStore, eventStore, productStore, undoRedo3DStore, versionStore } = useSceneContext();
    const { push3D } = undoRedo3DStore();
    const {
        updateAsset,
        getAssetById,
        rotatedObjects,
        setRotatedObjects,
        selectedAssets,
        setSelectedAssets,
        movedObjects,
        setMovedObjects,
        pastedObjects,
        setPastedObjects,
        duplicatedObjects,
        setDuplicatedObjects,
        initialStates,
        setInitialState,
    } = assetStore();
    const { updateAssetInScene } = useAssetResponseHandler();
    const { selectedVersion } = versionStore();

    const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("");
    const [isRotating, setIsRotating] = useState(false);
    const [isIndividualRotating, setIsIndividualRotating] = useState(false);
    const prevPointerPosition = useRef<THREE.Vector2 | null>(null);
    const rotationCenter = useRef<THREE.Vector3 | null>(null);
    const mouseButtonsDown = useRef<{ left: boolean; right: boolean }>({ left: false, right: false });
    const { contextAction, setContextAction } = useContextActionStore();
    const snapBaseRef = useRef<number | null>(null);
    const prevRotationRef = useRef<number | null>(null);
    const wasShiftHeldRef = useRef(false);

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

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

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

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

        let isPointerMoving = false;

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

        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 && rotatedObjects.length > 0 && event.button === 0) {
                event.preventDefault();
                placeRotatedAssets();
            }
            if (!isPointerMoving && rotatedObjects.length > 0 && event.button === 2) {
                event.preventDefault();
                resetToInitialRotations();
                clearSelection();
                setRotatedObjects([]);
            }
        };

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

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

            if (event.key.toLowerCase() === "r") {
                if (selectedAssets.length > 0) {
                    rotateAssets();
                }
            }

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

            if (event.key.toLowerCase() === "i") {
                if (rotatedObjects.length > 0) {
                    setIsIndividualRotating(!isIndividualRotating);
                }
            }

            if (event.key.toLowerCase() === "escape") {
                event.preventDefault();
                resetToInitialRotations();
                clearSelection();
                setRotatedObjects([]);
            }
        };

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

            if (keyCombination === "") {
                setKeyEvent("");
            } else if (keyCombination === "Ctrl" || keyCombination === "Ctrl+Shift" || keyCombination === "Shift") {
                setKeyEvent(keyCombination);
            }
            const currentPointer = new THREE.Vector2(pointer.x, pointer.y);
            prevPointerPosition.current = currentPointer.clone();
        };

        if (!toggleView && toolMode === "cursor") {
            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, scene, toggleView, toolMode, selectedAssets, rotatedObjects, pastedObjects, duplicatedObjects, movedObjects, keyEvent, initialStates, isIndividualRotating]);

    useEffect(() => {
        if (activeModule !== "builder" || toolMode !== "cursor" || toggleView) {
            resetToInitialRotations();
            setRotatedObjects([]);
        }
    }, [activeModule, toolMode, toggleView]);

    const resetToInitialRotations = useCallback(() => {
        setTimeout(() => {
            rotatedObjects.forEach((rotatedObject: THREE.Object3D) => {
                if (rotatedObject.userData.modelUuid && initialStates[rotatedObject.uuid]) {
                    const initialState = initialStates[rotatedObject.uuid];

                    updateAsset(rotatedObject.userData.modelUuid, {
                        position: initialState.position,
                        rotation: initialState.rotation,
                    });

                    rotatedObject.position.set(initialState.position[0], initialState.position[1], initialState.position[2]);
                    if (initialState.rotation) {
                        rotatedObject.rotation.set(initialState.rotation[0], initialState.rotation[1], initialState.rotation[2]);
                    }
                }
            });
        }, 50);
    }, [rotatedObjects, initialStates, updateAsset]);

    const resetToInitialRotation = useCallback(
        (modelUuid: string) => {
            setTimeout(() => {
                const rotatedObject = rotatedObjects.find((o: THREE.Object3D) => o.userData.modelUuid === modelUuid);

                if (!rotatedObject) return;

                const initialState = initialStates[rotatedObject.uuid];

                if (initialState) {
                    updateAsset(modelUuid, {
                        position: initialState.position,
                        rotation: initialState.rotation,
                    });

                    rotatedObject.position.set(initialState.position[0], initialState.position[1], initialState.position[2]);
                    if (initialState.rotation) {
                        rotatedObject.rotation.set(initialState.rotation[0], initialState.rotation[1], initialState.rotation[2]);
                    }
                }
            }, 50);
        },
        [rotatedObjects, initialStates, updateAsset]
    );

    useFrame(() => {
        if (!isRotating || rotatedObjects.length === 0) return;

        const currentPointer = new THREE.Vector2(pointer.x, pointer.y);

        if (mouseButtonsDown.current.left || mouseButtonsDown.current.right) {
            prevPointerPosition.current = currentPointer.clone();
            return;
        }

        if (prevPointerPosition.current && rotationCenter.current) {
            const center = rotationCenter.current;
            const deltaX = currentPointer.x - prevPointerPosition.current.x;

            rotatedObjects.forEach((obj: THREE.Object3D) => {
                if (obj.userData.modelUuid) {
                    const angleDelta = handleAssetRotationSnap({
                        object: obj,
                        pointerDeltaX: deltaX,
                        keyEvent,
                        snapBaseRef,
                        prevRotationRef,
                        wasShiftHeldRef,
                    });

                    if (!isIndividualRotating) {
                        const relativePosition = new THREE.Vector3().subVectors(obj.position, center);
                        const rotationMatrix = new THREE.Matrix4().makeRotationY(angleDelta);
                        relativePosition.applyMatrix4(rotationMatrix);
                        obj.position.copy(center).add(relativePosition);
                    }

                    const rotationQuat = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angleDelta);
                    obj.quaternion.multiply(rotationQuat);
                    obj.rotation.setFromQuaternion(obj.quaternion);
                }
            });

            prevPointerPosition.current = currentPointer.clone();
        }
    });

    const rotateAssets = useCallback(() => {
        const states: Record<string, { position: [number, number, number]; rotation: [number, number, number] }> = {};
        const positions: Record<string, THREE.Vector3> = {};

        const box = new THREE.Box3();
        selectedAssets.forEach((obj: THREE.Object3D) => box.expandByObject(obj));
        const center = new THREE.Vector3();
        box.getCenter(center);
        rotationCenter.current = center;

        selectedAssets.forEach((asset: THREE.Object3D) => {
            states[asset.uuid] = {
                position: asset.position.toArray(),
                rotation: [asset.rotation.x, asset.rotation.y, asset.rotation.z],
            };
            positions[asset.uuid] = new THREE.Vector3().copy(asset.position);
        });

        setInitialState(states);

        raycaster.setFromCamera(pointer, camera);

        prevPointerPosition.current = new THREE.Vector2(pointer.x, pointer.y);

        setRotatedObjects(selectedAssets);
        setIsRotating(true);
    }, [selectedAssets, camera, pointer, raycaster]);

    const placeRotatedAssets = useCallback(() => {
        if (rotatedObjects.length === 0) return;

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

        rotatedObjects.forEach((rotatedObject: THREE.Object3D) => {
            if (rotatedObject) {
                const assetUuid = rotatedObject.userData.modelUuid;
                const asset = getAssetById(assetUuid);
                if (!asset) return;
                const initialState = initialStates[assetUuid];

                const rotationArray: [number, number, number] = [rotatedObject.rotation.x, rotatedObject.rotation.y, rotatedObject.rotation.z];

                const positionArray: [number, number, number] = [rotatedObject.position.x, rotatedObject.position.y, rotatedObject.position.z];

                if (initialState) {
                    assetsToUpdate.push({
                        type: "Asset",
                        assetData: {
                            ...asset,
                            position: initialState.position,
                            rotation: initialState.rotation,
                        },
                        newData: {
                            ...asset,
                            position: positionArray,
                            rotation: rotationArray,
                        },
                        timeStap: new Date().toISOString(),
                    });
                }

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

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

                    if (eventData) {
                        eventStore.getState().updateEvent(rotatedObject.userData.modelUuid, {
                            position: positionArray,
                            rotation: rotationArray,
                        });
                    }

                    if (productData) {
                        const event = productStore.getState().updateEvent(productStore.getState().selectedProduct.productUuid, rotatedObject.userData.modelUuid, {
                            position: positionArray,
                            rotation: rotationArray,
                        });

                        if (event) {
                            updateBackend(productStore.getState().selectedProduct.productName, productStore.getState().selectedProduct.productUuid, projectId || "", event);
                        }

                        newFloorItem.eventData = eventData;
                    }
                }

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

                if (!builderSocket?.connected) {
                    // REST

                    setAssetsApi({
                        modelUuid: newFloorItem.modelUuid,
                        modelName: newFloorItem.modelName,
                        assetId: newFloorItem.assetId,
                        position: newFloorItem.position,
                        rotation: { x: rotatedObject.rotation.x, y: rotatedObject.rotation.y, z: rotatedObject.rotation.z },
                        isLocked: false,
                        isVisible: true,
                        versionId: selectedVersion?.versionId || "",
                        projectId: projectId,
                    })
                        .then((data) => {
                            if (!data.message || !data.data) {
                                echo.error(`Error rotating asset: ${newFloorItem.modelUuid}`);
                                resetToInitialRotation(newFloorItem.modelUuid);
                                clearSelection();
                                return;
                            }
                            if (data.message === "Model updated successfully" && data.data) {
                                const model: Asset = {
                                    modelUuid: data.data.modelUuid,
                                    modelName: data.data.modelName,
                                    assetId: data.data.assetId,
                                    position: data.data.position,
                                    rotation: [data.data.rotation.x, data.data.rotation.y, data.data.rotation.z],
                                    isLocked: data.data.isLocked,
                                    isCollidable: true,
                                    isVisible: data.data.isVisible,
                                    opacity: 1,
                                    eventData: data.data.eventData,
                                };

                                updateAssetInScene(model, () => {
                                    echo.log(`Rotated asset: ${model.modelName}`);
                                    clearSelection();
                                });
                            } else {
                                echo.error(`Error rotating asset: ${newFloorItem.modelUuid}`);
                                resetToInitialRotation(newFloorItem.modelUuid);
                                clearSelection();
                            }
                        })
                        .catch(() => {
                            echo.error(`Error rotating asset: ${newFloorItem.modelUuid}`);

                            resetToInitialRotation(newFloorItem.modelUuid);
                            clearSelection();
                        });
                } else {
                    // SOCKET

                    builderSocket.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,
            });
        }

        setIsRotating(false);
        setIsIndividualRotating(false);
        clearSelection();
    }, [rotatedObjects, eventStore, productStore, updateBackend, projectId, updateAsset, organization, builderSocket, selectedVersion, userId, initialStates]);

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

    return null;
}

export default RotateControls3D;
