import { toast } from 'react-toastify';
import * as THREE from 'three';

import * as Types from "../../../../types/world/worldTypes";
// import { deleteFloorItem } from '../../../../services/factoryBuilder/assest/floorAsset/deleteFloorItemApi';
import { Socket } from 'socket.io-client';
import { getFloorAssets } from '../../../../services/factoryBuilder/assest/floorAsset/getFloorItemsApi';
import { useEventsStore } from "../../../../store/simulation/useEventsStore";
import { useProductStore } from "../../../../store/simulation/useProductStore";

async function DeleteFloorItems(
    itemsGroup: Types.RefGroup,
    hoveredDeletableFloorItem: Types.RefMesh,
    setFloorItems: Types.setFloorItemSetState,
    socket: Socket<any>
): Promise<void> {

    ////////// Deleting the hovered Floor GLTF from the scene (itemsGroup.current) and from the floorItems and also update it in the localstorage //////////

    if (hoveredDeletableFloorItem.current) {

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

        const items = await getFloorAssets(organization);
        const removedItem = items.find(
            (item: { modelUuid: string }) => item.modelUuid === hoveredDeletableFloorItem.current?.uuid
        );

        if (!removedItem) {
            return
        }

        //REST

        // const response = await deleteFloorItem(organization, removedItem.modelUuid, removedItem.modelName);

        //SOCKET 

        const data = {
            organization: organization,
            modelUuid: removedItem.modelUuid,
            modelName: removedItem.modelName,
            socketId: socket.id
        }

        const response = socket.emit('v2:model-asset:delete', data)

        useEventsStore.getState().removeEvent(removedItem.modelUuid);
        useProductStore.getState().deleteEvent(removedItem.modelUuid);

        if (response) {
            const updatedItems = items.filter(
                (item: { modelUuid: string }) => item.modelUuid !== hoveredDeletableFloorItem.current?.uuid
            );

            const storedItems = JSON.parse(localStorage.getItem("FloorItems") || '[]');
            const updatedStoredItems = storedItems.filter((item: { modelUuid: string }) => item.modelUuid !== hoveredDeletableFloorItem.current?.uuid);
            localStorage.setItem("FloorItems", JSON.stringify(updatedStoredItems));

            if (hoveredDeletableFloorItem.current) {
                // Traverse and dispose of resources
                hoveredDeletableFloorItem.current.traverse((child: THREE.Object3D) => {
                    if (child instanceof THREE.Mesh) {
                        if (child.geometry) child.geometry.dispose();
                        if (Array.isArray(child.material)) {
                            child.material.forEach((material) => {
                                if (material.map) material.map.dispose();
                                material.dispose();
                            });
                        } else if (child.material) {
                            if (child.material.map) child.material.map.dispose();
                            child.material.dispose();
                        }
                    }
                });

                // Remove the object from the scene
                itemsGroup.current.remove(hoveredDeletableFloorItem.current);
            }
            setFloorItems(updatedItems);

            toast.success("Model Removed!");
        }
    }
}

export default DeleteFloorItems;
