import React, { useEffect, useMemo, useRef } from 'react';
import { useWallStore } from '../../../../store/builder/useWallStore'
import WallInstance from './instance/wallInstance';
import Line from '../../line/line';
import Point from '../../point/point';
import { useToggleView } from '../../../../store/builder/store';
import { Base, Geometry, Subtraction } from '@react-three/csg';
import { BoxGeometry } from 'three';

function WallInstances() {
    const { walls } = useWallStore();
    const { toggleView } = useToggleView();
    const ref = useRef<any>();
    const csg = useRef<any>();

    useEffect(() => {
        // console.log('walls: ', walls);
    }, [walls])

    const allPoints = useMemo(() => {
        const points: Point[] = [];
        const seenUuids = new Set<string>();

        walls.forEach(aisle => {
            aisle.points.forEach(point => {
                if (!seenUuids.has(point.pointUuid)) {
                    seenUuids.add(point.pointUuid);
                    points.push(point);
                }
            });
        });

        return points;
    }, [walls]);


    const box = useMemo(() => new BoxGeometry(), []);

    return (
        <>
            <group name='Walls-Group' ref={ref}>

                <mesh >
                    <Geometry ref={csg} computeVertexNormals useGroups>

                        <Base name="base" geometry={box} scale={[3, 3, 3]} />

                        {walls.map((wall) => (
                            <WallInstance key={wall.wallUuid} wall={wall} />
                        ))}


                        <Subtraction rotation={[0, Math.PI / 2, 0]} position={[-1.425, -0.45, 0]} scale={[1, 3, 1]}>
                            <Geometry>
                                <Base geometry={box} />
                            </Geometry>
                        </Subtraction>
                    </Geometry>
                </mesh>

            </group>

            {toggleView && (
                <>
                    <group name='Wall-Points-Group'>
                        {allPoints.map((point) => (
                            <Point key={point.pointUuid} point={point} />
                        ))}
                    </group>

                    <group name='Wall-Lines-Group'>
                        {walls.map((wall) => (
                            <React.Fragment key={wall.wallUuid}>
                                <Line points={wall.points} />
                            </React.Fragment>
                        ))}
                    </group>
                </>
            )}
        </>
    )
}

export default WallInstances
