import { TransformControls } from "@react-three/drei";
import * as THREE from "three";
import { useSelectedFloorItem, useObjectPosition, useObjectRotation, useFloorItems, useActiveTool, useSocketStore } from "../../../../store/builder/store";
import { useThree } from "@react-three/fiber";

import * as Types from '../../../../types/world/worldTypes';
import { useEffect, useState } from "react";
import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifierKeys";
import { useEventsStore } from "../../../../store/simulation/useEventsStore";
import { useProductStore } from "../../../../store/simulation/useProductStore";
import { useSelectedProduct } from "../../../../store/simulation/useSimulationStore";
import { upsertProductOrEventApi } from "../../../../services/simulation/products/UpsertProductOrEventApi";
import { setFloorItemApi } from "../../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi";
import { useParams } from "react-router-dom";

export default function TransformControl() {
    const state = useThree();
    const [transformMode, setTransformMode] = useState<"translate" | "rotate" | null>(null);
    const { selectedFloorItem, setSelectedFloorItem } = useSelectedFloorItem();
    const { setObjectPosition } = useObjectPosition();
    const { setObjectRotation } = useObjectRotation();
    const { setFloorItems } = useFloorItems();
    const { activeTool } = useActiveTool();
    const { socket } = useSocketStore();
    const { selectedProduct } = useSelectedProduct();

    const email = localStorage.getItem('email')
    const organization = (email!.split("@")[1]).split(".")[0];
    const userId = localStorage.getItem("userId");
    const { projectId } = useParams();

    const updateBackend = (
        productName: string,
        productId: string,
        organization: string,
        eventData: EventsSchema
    ) => {
        upsertProductOrEventApi({
            productName: productName,
            productId: productId,
            organization: organization,
            eventDatas: eventData,
        });
    };

    function handleObjectChange() {
        if (selectedFloorItem) {
            setObjectPosition(selectedFloorItem.position);
            setObjectRotation({
                x: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.x),
                y: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.y),
                z: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.z),
            });
        }
    }

    function handleMouseUp() {
        if (selectedFloorItem) {
            setObjectPosition(selectedFloorItem.position);
            setObjectRotation({
                x: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.x),
                y: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.y),
                z: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.z),
            });
        }
        setFloorItems((prevItems: Types.FloorItems) => {
            if (!prevItems) {
                return
            }
            let updatedItem: any = null;
            const updatedItems = prevItems.map((item) => {
                if (item.modelUuid === selectedFloorItem?.uuid) {
                    updatedItem = {
                        ...item,
                        position: [selectedFloorItem.position.x, 0, selectedFloorItem.position.z] as [number, number, number],
                        rotation: { x: selectedFloorItem.rotation.x, y: selectedFloorItem.rotation.y, z: selectedFloorItem.rotation.z },
                    };
                    return updatedItem;
                }
                return item;
            });
            if (updatedItem && selectedFloorItem) {
                if (updatedItem.eventData) {
                    const eventData = useEventsStore.getState().getEventByModelUuid(updatedItem.modelUuid);
                    const productData = useProductStore.getState().getEventByModelUuid(selectedProduct.productId, updatedItem.modelUuid);

                    if (eventData) {
                        useEventsStore.getState().updateEvent(updatedItem.modelUuid, {
                            position: [selectedFloorItem.position.x, 0, selectedFloorItem.position.z],
                            rotation: [selectedFloorItem.rotation.x, selectedFloorItem.rotation.y, selectedFloorItem.rotation.z],
                        });
                    }

                    if (productData) {
                        const event = useProductStore
                            .getState()
                            .updateEvent(
                                selectedProduct.productId,
                                updatedItem.modelUuid,
                                {
                                    position: [selectedFloorItem.position.x, 0, selectedFloorItem.position.z],
                                    rotation: [selectedFloorItem.rotation.x, selectedFloorItem.rotation.y, selectedFloorItem.rotation.z],
                                }
                            );

                        if (event) {
                            updateBackend(
                                selectedProduct.productName,
                                selectedProduct.productId,
                                organization,
                                event
                            );
                        }

                        updatedItem.eventData = eventData;
                    }
                }

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

                // REST

                // setFloorItemApi(
                //     organization,
                //     updatedItem.modelUuid,
                //     updatedItem.modelName,
                //     updatedItem.modelfileid,
                //     [selectedFloorItem.position.x, 0, selectedFloorItem.position.z,],
                //     { "x": selectedFloorItem.rotation.x, "y": selectedFloorItem.rotation.y, "z": selectedFloorItem.rotation.z },
                //     false,
                //     true,
                // );

                // SOCKET

                const data = {
                    organization: organization,
                    modelUuid: updatedItem.modelUuid,
                    modelName: updatedItem.modelName,
                    modelfileID: updatedItem.modelfileID,
                    position: [selectedFloorItem.position.x, 0, selectedFloorItem.position.z],
                    rotation: { "x": selectedFloorItem.rotation.x, "y": selectedFloorItem.rotation.y, "z": selectedFloorItem.rotation.z },
                    isLocked: false,
                    isVisible: true,
                    socketId: socket.id,
                    projectId, userId
                }

                socket.emit("v1:model-asset:add", data);
            }
            localStorage.setItem("FloorItems", JSON.stringify(updatedItems));
            return updatedItems;
        });
    }

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            const keyCombination = detectModifierKeys(e);
            if (!selectedFloorItem) return;
            if (keyCombination === "G") {
                setTransformMode((prev) => (prev === "translate" ? null : "translate"));
            }
            if (keyCombination === "R") {
                setTransformMode((prev) => (prev === "rotate" ? null : "rotate"));
            }
        };

        if (selectedFloorItem) {
            window.addEventListener("keydown", handleKeyDown);
            setObjectPosition(selectedFloorItem.position);
            setObjectRotation({
                x: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.x),
                y: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.y),
                z: THREE.MathUtils.radToDeg(selectedFloorItem.rotation.z),
            });
        } else {
            setTransformMode(null);
        }

        return () => {
            window.removeEventListener("keydown", handleKeyDown);
        };
    }, [selectedFloorItem]);

    useEffect(() => {
        if (activeTool === "delete") {
            if (state.controls) {
                const target = (state.controls as any).getTarget(new THREE.Vector3());
                (state.controls as any).setTarget(target.x, 0, target.z, true);
            }
            setSelectedFloorItem(null);
            setObjectPosition({ x: undefined, y: undefined, z: undefined });
            setObjectRotation({ x: undefined, y: undefined, z: undefined });
        }
    }, [activeTool]);

    return (
        <>
            {(selectedFloorItem && transformMode) &&
                <TransformControls
                    showX={transformMode === "translate"}
                    showY={transformMode === "rotate"}
                    showZ={transformMode === "translate"}
                    object={selectedFloorItem}
                    mode={transformMode}
                    onObjectChange={handleObjectChange}
                    onMouseUp={handleMouseUp}
                />
            }
        </>
    );
}
