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 { upsertProductOrEventApi } from "../../../../../services/simulation/products/UpsertProductOrEventApi";
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 { detectModifierKeys } from "../../../../../utils/shortcutkeys/detectModifierKeys";
import { handleAssetRotationSnap } from "./functions/handleAssetRotationSnap";

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

function RotateControls3D() {
    const { camera, gl, scene, pointer, raycaster } = useThree();

    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, rotatedObjects, setRotatedObjects, movedObjects, setMovedObjects, pastedObjects, setPastedObjects, duplicatedObjects, setDuplicatedObjects } = assetStore();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();

    const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("");
    const [initialRotations, setInitialRotations] = useState<Record<string, THREE.Euler>>({});
    const [initialPositions, setInitialPositions] = useState<Record<string, THREE.Vector3>>({});
    const [isRotating, setIsRotating] = 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() === "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) {
            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, selectedAssets, rotatedObjects, pastedObjects, duplicatedObjects, movedObjects, keyEvent, initialPositions, initialRotations]);

    const resetToInitialRotations = useCallback(() => {
        setTimeout(() => {
            rotatedObjects.forEach((obj: THREE.Object3D) => {
                const uuid = obj.uuid;
                if (obj.userData.modelUuid) {
                    const initialRotation = initialRotations[uuid];
                    const initialPosition = initialPositions[uuid];

                    if (initialRotation && initialPosition) {
                        const rotationArray: [number, number, number] = [initialRotation.x, initialRotation.y, initialRotation.z,];
                        const positionArray: [number, number, number] = [initialPosition.x, initialPosition.y, initialPosition.z,];

                        updateAsset(obj.userData.modelUuid, {
                            rotation: rotationArray,
                            position: positionArray,
                        });

                        obj.rotation.copy(initialRotation);
                        obj.position.copy(initialPosition);
                    }
                }
            });
        }, 50)
    }, [rotatedObjects, initialRotations, initialPositions, 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
                    });

                    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 rotations: Record<string, THREE.Euler> = {};
        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((obj: THREE.Object3D) => {
            rotations[obj.uuid] = new THREE.Euler().copy(obj.rotation);
            positions[obj.uuid] = new THREE.Vector3().copy(obj.position);
        });

        setInitialRotations(rotations);
        setInitialPositions(positions);

        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((obj: THREE.Object3D) => {
            if (obj && obj.userData.modelUuid) {
                const asset = assetStore.getState().getAssetById(obj.userData.modelUuid);
                if (!asset) return;

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

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

                if (initialRotations[obj.uuid] && initialPositions[obj.uuid]) {
                    assetsToUpdate.push({
                        type: "Asset",
                        assetData: {
                            ...asset,
                            position: [
                                initialPositions[obj.uuid].x,
                                initialPositions[obj.uuid].y,
                                initialPositions[obj.uuid].z
                            ],
                            rotation: [
                                initialRotations[obj.uuid].x,
                                initialRotations[obj.uuid].y,
                                initialRotations[obj.uuid].z
                            ]
                        },
                        newData: {
                            ...asset,
                            position: positionArray,
                            rotation: rotationArray
                        },
                        timeStap: new Date().toISOString()
                    });
                }

                const newFloorItem: Types.FloorItemType = {
                    modelUuid: obj.userData.modelUuid,
                    modelName: obj.userData.modelName,
                    assetId: obj.userData.assetId,
                    position: positionArray,
                    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: positionArray,
                            rotation: rotationArray,
                        });
                    }

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

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

                        newFloorItem.eventData = eventData;
                    }
                }

                updateAsset(obj.userData.modelUuid, {
                    position: positionArray,
                    rotation: rotationArray,
                });

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

                //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
            });
        }

        setIsRotating(false);
        clearSelection();
    }, [rotatedObjects, eventStore, productStore, selectedProduct, updateBackend, projectId, updateAsset, organization, socket, selectedVersion, userId]);

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

    return null;
}

export default RotateControls3D;