import { Geometry } from "@react-three/csg";
import { useDeleteTool, useSelectedWallItem, useToggleView, useTransformMode, useWallItems, useWalls } from "../../../store/store";
import handleMeshDown from "../eventFunctions/handleMeshDown";
import handleMeshMissed from "../eventFunctions/handleMeshMissed";
import WallsMesh from "./wallsMesh";
import WallItemsGroup from "./wallItemsGroup";
import { useEffect } from "react";


const WallsAndWallItems = ({ CSGGroup, AssetConfigurations, setSelectedItemsIndex, selectedItemsIndex, currentWallItem, csg, lines, hoveredDeletableWallItem }: any) => {
    const { walls, setWalls } = useWalls();
    const { wallItems, setWallItems } = useWallItems();
    const { toggleView, setToggleView } = useToggleView();
    const { deleteTool, setDeleteTool } = useDeleteTool();
    const { transformMode, setTransformMode } = useTransformMode();
    const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();

    useEffect(() => {
        if (transformMode === null) {
            if (!deleteTool) {
                handleMeshMissed(currentWallItem, setSelectedWallItem, setSelectedItemsIndex);
                setSelectedWallItem(null);
                setSelectedItemsIndex(null);
            }
        }
    }, [transformMode])

    return (
        <mesh
            ref={CSGGroup as any}
            name="Walls"
            key={walls.length}
            receiveShadow
            visible={!toggleView}
            onClick={(event) => {
                if (!deleteTool && transformMode !== null) {
                    handleMeshDown(event, currentWallItem, setSelectedWallItem, setSelectedItemsIndex, wallItems, toggleView);
                }
            }}
            onPointerMissed={() => {
                if (!deleteTool) {
                    handleMeshMissed(currentWallItem, setSelectedWallItem, setSelectedItemsIndex);
                    setSelectedWallItem(null);
                    setSelectedItemsIndex(null);
                }
            }}
        >
            <Geometry ref={csg as any} computeVertexNormals useGroups>
                <WallsMesh lines={lines} />
                <WallItemsGroup currentWallItem={currentWallItem} AssetConfigurations={AssetConfigurations} hoveredDeletableWallItem={hoveredDeletableWallItem} selectedItemsIndex={selectedItemsIndex} setSelectedItemsIndex={setSelectedItemsIndex} CSGGroup={CSGGroup} />
            </Geometry>
        </mesh>
    )
}

export default WallsAndWallItems;