import { useThree } from "@react-three/fiber";
import React, { useState, useEffect } from "react";
import { useAsset3dWidget, useSocketStore, 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";
import { generateUniqueId } from "../../../functions/generateUniqueId";
import { adding3dWidgets } from "../../../services/realTimeVisulization/zoneData/add3dWidget";
import { get3dWidgetZoneData } from "../../../services/realTimeVisulization/zoneData/get3dWidgetData";
import { use3DWidget } from "../../../store/useDroppedObjectsStore";
import { useZoneWidgetStore } from "../../../store/useZone3DWidgetStore";

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

    // ✅ Use Zustand Store instead of useState
    const { zoneWidgetData, setZoneWidgetData, addWidget } = useZoneWidgetStore();
    const { setWidgets3D } = use3DWidget();
    const { visualizationSocket } = useSocketStore();

    useEffect(() => {
        if (activeModule !== "visualization") return;
        if (!selectedZone.zoneId) return;

    const email = localStorage.getItem("email") || "";
    const organization = email?.split("@")[1]?.split(".")[0];

        async function get3dWidgetData() {
            let result = await get3dWidgetZoneData(selectedZone.zoneId, organization);
            console.log('result: ', result);
            setWidgets3D(result);

            const formattedWidgets = result.map((widget: any) => ({
                id: widget.id,
                type: widget.type,
                position: widget.position,
            }));

            setZoneWidgetData(selectedZone.zoneId, formattedWidgets);
        }

        get3dWidgetData();
    }, [selectedZone.zoneId, activeModule]);

    useEffect(() => {
        if (activeModule !== "visualization") return;
        if (widgetSubOption === "Floating" || widgetSubOption === "2D") return;
        if (selectedZone.zoneName === "") return;

        const canvasElement = gl.domElement;

        const onDrop = async (event: DragEvent) => {
            event.preventDefault();

            const email = localStorage.getItem("email") || "";
            const organization = email?.split("@")[1]?.split(".")[0];
            if (!widgetSelect.startsWith("ui")) return;
            const group1 = scene.getObjectByName("itemsGroup");
            if (!group1) return;

            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;
                const newWidget = {
                    id: generateUniqueId(),
                    type: widgetSelect,
                    position: [x, y, z] as [number, number, number],
                };

                let add3dWidget = {
                    organization: organization,
                    widget: newWidget,
                    zoneId: selectedZone.zoneId
                }
                console.log('add3dWidget: ', add3dWidget);
                if (visualizationSocket) {
                    visualizationSocket.emit("v2:viz-3D-widget:add", add3dWidget)
                }

                // let response = await adding3dWidgets(selectedZone.zoneId, organization, newWidget);
                // console.log('response: ', response);

                // if (response.message === "Widget created successfully") {
                addWidget(selectedZone.zoneId, newWidget);
                // }
            }
        };

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

    const activeZoneWidgets = zoneWidgetData[selectedZone.zoneId] || [];

    return (
        <>
            {activeZoneWidgets.map(({ id, type, position }) => {
                console.log('Typeeeeeeeeeeee',type);
                switch (type) {
                    case "ui-Widget 1":
                        return <ProductionCapacity key={id} id={id} type={type} position={position} />;
                    case "ui-Widget 2":
                        return <ReturnOfInvestment key={id} id={id} type={type} position={position} />;
                    case "ui-Widget 3":
                        return <StateWorking key={id} id={id} type={type} position={position} />;
                    case "ui-Widget 4":
                        return <Throughput key={id} id={id} type={type} position={position} />;
                    default:
                        return null;
                }
            })}
        </>
    );
}
