import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { MathUtils, Vector3 } from "three";
import { useThree } from "@react-three/fiber";
import { useSceneContext } from "../../scene/sceneContext";
import { useSocketStore } from "../../../store/socket/useSocketStore";
import { useSelectedItem, useToggleView } from "../../../store/builder/store";
import useModuleStore from "../../../store/ui/useModuleStore";
import useWallAssetResponseHandler from "../../collaboration/responseHandler/useWallAssetResponseHandler";
import { getUserData } from "../../../functions/getUserData";
import closestPointOnLineSegment from "../line/helpers/getClosestPointOnLineSegment";

import { upsertWallAssetApi } from "../../../services/factoryBuilder/asset/wallAsset/upsertWallAssetApi";

function WallAssetCreator() {
    const { builderSocket } = useSocketStore();
    const { pointer, camera, raycaster, scene, gl } = useThree();
    const { toggleView } = useToggleView();
    const { activeModule } = useModuleStore();
    const { versionStore } = useSceneContext();
    const { addWallAssetToScene } = useWallAssetResponseHandler();
    const { selectedItem, setSelectedItem } = useSelectedItem();
    const { selectedVersion } = versionStore();
    const { userId, organization } = getUserData();
    const { projectId } = useParams();

    useEffect(() => {
        const canvasElement = gl.domElement;

        const onDrop = (event: DragEvent) => {
            if (!event.dataTransfer?.files[0]) return;
            if (selectedItem.id !== "" && event.dataTransfer?.files[0] && selectedItem.category === "Fenestration") {
                pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
                pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;

                raycaster.setFromCamera(pointer, camera);
                const intersects = raycaster.intersectObjects(scene.children, true);
                const intersect = intersects.find((intersect) => intersect.object.name.includes("WallReference"));

                if (intersect) {
                    const wall = intersect.object.userData as Wall;
                    const closestPoint = closestPointOnLineSegment(
                        new Vector3(intersect.point.x, 0, intersect.point.z),
                        new Vector3(...wall.points[0].position),
                        new Vector3(...wall.points[1].position)
                    );

                    const wallRotation = intersect.object.rotation.clone();

                    const newWallAsset: WallAsset = {
                        modelName: selectedItem.name,
                        modelUuid: MathUtils.generateUUID(),
                        wallUuid: wall.wallUuid,
                        wallAssetType: selectedItem.subType,
                        assetId: selectedItem.id,
                        position: [closestPoint.x, selectedItem.subType === "fixedMove" ? 0 : intersect.point.y, closestPoint.z],
                        rotation: [wallRotation.x, wallRotation.y, wallRotation.z],
                        isLocked: false,
                        isVisible: true,
                        opacity: 1,
                    };

                    if (projectId) {
                        if (!builderSocket?.connected) {
                            // API

                            upsertWallAssetApi(projectId, selectedVersion?.versionId || "", newWallAsset)
                                .then((data) => {
                                    if (!data.message) {
                                        echo.error(`Error adding wallAsset: ${newWallAsset.modelName}`);
                                        return;
                                    }
                                    if (data.message === "WallAsset Created Successfully" && data.data) {
                                        addWallAssetToScene(newWallAsset, () => {
                                            echo.log(`Added wallAsset: ${newWallAsset.modelName}`);
                                        });
                                    } else {
                                        echo.error(`Error adding wallAsset: ${newWallAsset.modelName}`);
                                    }
                                })
                                .catch(() => {
                                    echo.error(`Error adding wallAsset: ${newWallAsset.modelName}`);
                                });
                        } else {
                            // SOCKET

                            const data = {
                                wallAssetData: newWallAsset,
                                projectId: projectId,
                                versionId: selectedVersion?.versionId || "",
                                userId: userId,
                                organization: organization,
                            };

                            builderSocket.emit("v1:wall-asset:add", data);
                        }
                    }
                }
            }
        };

        if (!toggleView && activeModule === "builder") {
            canvasElement.addEventListener("drop", onDrop);
        }

        return () => {
            canvasElement.removeEventListener("drop", onDrop);
        };
    }, [gl, camera, toggleView, activeModule, builderSocket, selectedItem, setSelectedItem]);

    return <></>;
}

export default WallAssetCreator;
