import React, { useEffect, useMemo } 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 { Geometry } from '@react-three/csg';

function WallInstances() {
    const { walls } = useWallStore();
    const { toggleView } = useToggleView();

    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'>
                <Geometry computeVertexNormals useGroups>
                    {walls.map((wall) => (
                        <WallInstance key={wall.wallUuid} wall={wall} />
                    ))}
                </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