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

import * as Types from '../../../types/world/worldTypes';
import { useEffect } from "react";

export default function TransformControl() {
    const state = useThree();
    const { selectedFloorItem, setselectedFloorItem } = useselectedFloorItem();
    const { objectPosition, setObjectPosition } = useObjectPosition();
    const { objectScale, setObjectScale } = useObjectScale();
    const { objectRotation, setObjectRotation } = useObjectRotation();
    const { transformMode, setTransformMode } = useTransformMode();
    const { floorItems, setFloorItems } = useFloorItems();
    const { activeTool, setActiveTool } = useActiveTool();
    const { socket } = useSocketStore();

    function handleObjectChange() {
        if (selectedFloorItem && transformMode) {
            setObjectPosition(selectedFloorItem.position);
            setObjectScale(selectedFloorItem.scale);
            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);
            setObjectScale(selectedFloorItem.scale);
            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, selectedFloorItem.position.y, 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) {
                const email = localStorage.getItem('email')
                const organization = (email!.split("@")[1]).split(".")[0];

                //REST

                // setFloorItemApi(
                //     organization,
                //     updatedItem.modeluuid,
                //     updatedItem.modelname,
                //     [selectedFloorItem.position.x, selectedFloorItem.position.y, 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,
                    position: [selectedFloorItem.position.x, selectedFloorItem.position.y, selectedFloorItem.position.z],
                    rotation: { "x": selectedFloorItem.rotation.x, "y": selectedFloorItem.rotation.y, "z": selectedFloorItem.rotation.z },
                    isLocked: false,
                    isVisible: true,
                    socketId: socket.id
                }

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

    useEffect(() => {
        if (activeTool === "Add pillar" || 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 });
                setObjectScale({ x: undefined, y: undefined, z: undefined });
                setObjectRotation({ x: undefined, y: undefined, z: undefined });
            }
        }
    }, [activeTool]);

    return (
        <>
            {(selectedFloorItem && transformMode) &&
                <TransformControls
                    object={selectedFloorItem}
                    mode={transformMode}
                    onObjectChange={handleObjectChange}
                    onMouseUp={handleMouseUp}
                />
            }
        </>
    );
}
