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>();

    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]);

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

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

                    {/* <Base geometry={new BoxGeometry()} >
                        <meshStandardMaterial />
                    </Base>

                    <Geometry>
                        <Subtraction scale={[5, 11, 5]} >
                            <Geometry>
                                <Base geometry={new BoxGeometry()} />
                            </Geometry>
                        </Subtraction>
                    </Geometry> */}
                </Geometry>
            </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