
import { useThree } from "@react-three/fiber";
import React, { useState, useEffect } from "react";
import { useAsset3dWidget } from "../../../store/store";
import useModuleStore from "../../../store/useModuleStore";
import { ThreeState } from "../../../types/world/worldTypes";
import * as THREE from "three";
import Throughput from "../../layout/3D-cards/cards/Throughput";
import ProductionCapacity from "../../layout/3D-cards/cards/ProductionCapacity";
import ReturnOfInvestment from "../../layout/3D-cards/cards/ReturnOfInvestment";
import StateWorking from "../../layout/3D-cards/cards/StateWorking";

export default function Dropped3dWidgets() {
    const { widgetSelect } = useAsset3dWidget();
    const { activeModule } = useModuleStore();
    const { raycaster, gl, scene }: ThreeState = useThree();

    // 🔥 Store multiple instances per widget type
    const [widgetPositions, setWidgetPositions] = useState<Record<string, [number, number, number][]>>({});

    useEffect(() => {
        if (activeModule !== "visualization") return;
        const canvasElement = gl.domElement;

        const onDrop = (event: DragEvent) => {
            event.preventDefault(); // Prevent default browser behavior

            if (!widgetSelect.startsWith("ui")) return;


            const group1 = scene.getObjectByName("itemsGroup");
            if (!group1) return;



            const Assets = group1.children
                .map((val) => scene.getObjectByProperty("uuid", val.uuid))
                .filter(Boolean) as THREE.Object3D[];


            const intersects = raycaster.intersectObjects(Assets);

            if (intersects.length > 0) {
                const { x, y, z } = intersects[0].point;


                // ✅ Allow multiple instances by storing positions in an array
                setWidgetPositions((prev) => ({
                    ...prev,
                    [widgetSelect]: [...(prev[widgetSelect] || []), [x, y, z]],
                }));
            }
        };

        canvasElement.addEventListener("drop", onDrop);

        return () => {
            canvasElement.removeEventListener("drop", onDrop);
        };
    }, [widgetSelect, activeModule]);

    return (
        <>
            {widgetPositions["ui-Widget 1"]?.map((pos, index) => (
                <ProductionCapacity key={`Widget1-${index}`} position={pos} />
            ))}
            {widgetPositions["ui-Widget 2"]?.map((pos, index) => (
                <ReturnOfInvestment key={`Widget2-${index}`} position={pos} />
            ))}
            {widgetPositions["ui-Widget 3"]?.map((pos, index) => (
                <StateWorking key={`Widget3-${index}`} position={pos} />
            ))}
            {widgetPositions["ui-Widget 4"]?.map((pos, index) => (
                <Throughput key={`Widget4-${index}`} position={pos} />
            ))}
        </>
    );
}

