import * as THREE from 'three';
import { Decal } from '@react-three/drei'
import { useLoader } from '@react-three/fiber';
import { useToggleView } from '../../../store/builder/store';
import { useBuilderStore } from '../../../store/builder/useBuilderStore';

import defaultMaterial from '../../../assets/textures/floor/wall-tex.png';
import useModuleStore from '../../../store/useModuleStore';

function DecalInstance({ visible = true, decal, zPosition = decal.decalPosition[2] }: { visible?: boolean, decal: Decal, zPosition?: number }) {
    const { setSelectedWall, setSelectedFloor, selectedDecal, setSelectedDecal } = useBuilderStore();
    const { togglView } = useToggleView();
    const { activeModule } = useModuleStore();
    const material = useLoader(THREE.TextureLoader, defaultMaterial);

    return (
        <Decal
            // debug
            visible={visible}
            position={[decal.decalPosition[0], decal.decalPosition[1], zPosition]}
            rotation={[0, 0, decal.decalRotation]}
            scale={[decal.decalScale, decal.decalScale, 0.01]}
            userData={decal}
            onClick={(e) => {
                if (visible && !togglView && activeModule === 'builder') {
                    if (e.object.userData.decalUuid) {
                        e.stopPropagation();
                        setSelectedDecal(e.object);
                        setSelectedWall(null);
                        setSelectedFloor(null);
                    }
                }
            }}
            onPointerMissed={() => {
                if (selectedDecal && selectedDecal.userData.decalUuid === decal.decalUuid) {
                    setSelectedDecal(null);
                }
            }}
        >
            <meshBasicMaterial
                map={material}
                side={THREE.DoubleSide}
                polygonOffset
                polygonOffsetFactor={-1}
            />
        </Decal>
    )
}

export default DecalInstance