
import { useThree } from "@react-three/fiber";
import React, { useState, useEffect } from "react";
import { useAsset3dWidget, useWidgetSubOption } 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";
import { useSelectedZoneStore } from "../../../store/useZoneStore";

export default function Dropped3dWidgets() {
    const { widgetSelect, setWidgetSelect } = useAsset3dWidget();
    const { activeModule } = useModuleStore();
    const { raycaster, gl, scene }: ThreeState = useThree();
    const { selectedZone } = useSelectedZoneStore(); // Get currently selected zone
    const { widgetSubOption, setWidgetSubOption } = useWidgetSubOption()
    // 🔥 Store widget positions per zone
    const [zoneWidgets, setZoneWidgets] = useState<Record<
        string, // Zone ID
        Record<string, [number, number, number][]> // Widget type -> Positions array
    >>({});


    useEffect(() => {
        if (widgetSubOption === "Floating") return
        // if (activeModule !== "visualization") return;
        const canvasElement = gl.domElement;
        const onDrop = (event: DragEvent) => {
            event.preventDefault(); // Prevent default browser behavior
            if (widgetSubOption === "3D") {
                if (selectedZone.zoneName === "") return
                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(scene.children, true).filter(
                    (intersect) =>
                        !intersect.object.name.includes("Roof") &&
                        !intersect.object.name.includes("agv-collider") &&
                        !intersect.object.name.includes("MeasurementReference") &&
                        !intersect.object.userData.isPathObject &&
                        !(intersect.object.type === "GridHelper")
                );
                if (intersects.length > 0) {
                    const { x, y, z } = intersects[0].point;

                    setZoneWidgets((prev) => ({
                        ...prev,
                        [selectedZone.zoneId]: {
                            ...(prev[selectedZone.zoneId] || {}),
                            [widgetSelect]: [...(prev[selectedZone.zoneId]?.[widgetSelect] || []), [x, y, z]],
                        },
                    }));
                }
            }
        };

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

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


