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

import defaultMaterial from '../../../assets/textures/floor/wall-tex.png';
import useModuleStore from '../../../store/useModuleStore';
import { useSceneContext } from '../../scene/sceneContext';
import { useEffect } from 'react';
import { getUserData } from '../../../functions/getUserData';
import { useVersionContext } from '../version/versionContext';
import { useParams } from 'react-router-dom';

// import { upsertWallApi } from '../../../services/factoryBuilder/wall/upsertWallApi';
// import { upsertFloorApi } from '../../../services/factoryBuilder/floor/upsertFloorApi';

function DecalInstance({ parent, visible = true, decal, zPosition = decal.decalPosition[2] }: { parent: Wall | Floor; visible?: boolean, decal: Decal, zPosition?: number }) {
    const { setSelectedWall, setSelectedFloor, selectedDecal, deletableDecal, setSelectedDecal, setDeletableDecal } = useBuilderStore();
    const { wallStore, floorStore } = useSceneContext();
    const { removeDecal: removeDecalFromWall } = wallStore();
    const { removeDecal: removeDecalFromFloor } = floorStore();
    const { toolMode } = useToolMode();
    const { toggleView } = useToggleView();
    const { activeModule } = useModuleStore();
    const { userId, organization } = getUserData();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { projectId } = useParams();
    const { socket } = useSocketStore();
    const material = useLoader(THREE.TextureLoader, defaultMaterial);

    useEffect(() => {
        if (!toggleView && activeModule === 'builder') {
            if (toolMode !== 'cursor') {
                if (selectedDecal) setSelectedDecal(null);
            }
            if (toolMode !== '3D-Delete') {
                if (deletableDecal) setDeletableDecal(null);
            }
        } else {
            if (selectedDecal) setSelectedDecal(null);
            if (deletableDecal) setDeletableDecal(null);
        }
    }, [toggleView, toolMode, activeModule, selectedDecal, deletableDecal]);

    const deleteDecal = (decalUuid: string, parent: Wall | Floor) => {
        if ('wallUuid' in parent) {
            const updatedWall = removeDecalFromWall(decalUuid);

            if (projectId && updatedWall) {
                // API

                // upsertWallApi(projectId, selectedVersion?.versionId || '', updatedWall);

                // SOCKET 

                const data = {
                    wallData: updatedWall,
                    projectId: projectId,
                    versionId: selectedVersion?.versionId || '',
                    userId: userId,
                    organization: organization
                }

                socket.emit('v1:model-Wall:add', data);
            }
        } else if ('floorUuid' in parent) {
            const updatedFloor = removeDecalFromFloor(decalUuid);

            if (projectId && updatedFloor) {
                // API

                // upsertFloorApi(projectId, selectedVersion?.versionId || '', updatedFloor);

                // SOCKET

                const data = {
                    floorData: updatedFloor,
                    projectId: projectId,
                    versionId: selectedVersion?.versionId || '',
                    userId: userId,
                    organization: organization
                }

                socket.emit('v1:model-Floor:add', data);
            }
        }
    }

    return (
        <Decal
            // debug
            visible={visible}
            position={[decal.decalPosition[0], decal.decalPosition[1], zPosition]}
            rotation={[0, 0, 0]}
            scale={[decal.decalScale, decal.decalScale, 0.01]}
            userData={decal}
            onClick={(e) => {
                if (visible && !toggleView && activeModule === 'builder') {
                    if (e.object.userData.decalUuid) {
                        e.stopPropagation();
                        if (toolMode === 'cursor') {
                            setSelectedDecal(e.object);
                            setSelectedWall(null);
                            setSelectedFloor(null);
                        } else if (toolMode === '3D-Delete') {
                            deleteDecal(e.object.userData.decalUuid, parent);
                        }
                    }
                }
            }}
            onPointerEnter={(e) => {
                if (visible && !toggleView && activeModule === 'builder') {
                    if (e.object.userData.decalUuid) {
                        e.stopPropagation();
                        if (toolMode === '3D-Delete') {
                            setDeletableDecal(e.object);
                        }
                    }
                }
            }}
            onPointerLeave={(e) => {
                if (visible && !toggleView && activeModule === 'builder') {
                    if (e.object.userData.decalUuid) {
                        e.stopPropagation();
                        if (toolMode === '3D-Delete' && deletableDecal && deletableDecal?.userData.decalUuid === e.object.userData.decalUuid) {
                            setDeletableDecal(null);
                        }
                    }
                }
            }}
            onPointerMissed={() => {
                if (selectedDecal && selectedDecal.userData.decalUuid === decal.decalUuid) {
                    setSelectedDecal(null);
                }
            }}
        >
            <meshBasicMaterial
                map={material}
                side={THREE.DoubleSide}
                polygonOffset
                polygonOffsetFactor={-1}
            />
        </Decal>
    )
}

export default DecalInstance