import React, { useMemo } from 'react';
import { useToggleView } from '../../../../store/builder/store';
import AisleInstance from './instance/aisleInstance';
import Point from '../../point/point';
import { Html } from '@react-three/drei';
import { Vector3 } from 'three';
import { useSceneContext } from '../../../scene/sceneContext';

function AisleInstances() {
    const { aisleStore } = useSceneContext();
    const { aisles } = aisleStore();
    const { toggleView } = useToggleView();

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

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

        return points;
    }, [aisles]);

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

            <group name='Aisles-Group'>
                {aisles.map((aisle) => {
                    const textPosition = new Vector3().addVectors(new Vector3(...aisle.points[0].position), new Vector3(...aisle.points[1].position)).divideScalar(2);
                    const distance = new Vector3(...aisle.points[0].position).distanceTo(new Vector3(...aisle.points[1].position));

                    return (
                        < React.Fragment key={aisle.aisleUuid}>
                            <AisleInstance aisle={aisle} key={aisle.aisleUuid} />

                            {toggleView &&
                                <Html
                                    key={`${aisle.points[0].pointUuid}_${aisle.points[1].pointUuid}`}
                                    userData={aisle}
                                    position={[textPosition.x, 1, textPosition.z]}
                                    wrapperClass="distance-text-wrapper"
                                    className="distance-text"
                                    zIndexRange={[1, 0]}
                                    prepend
                                    sprite
                                >
                                    <div
                                        key={aisle.aisleUuid}
                                        className={`distance ${aisle.aisleUuid}`}
                                    >
                                        {distance.toFixed(2)} m
                                    </div>
                                </Html>
                            }
                        </React.Fragment>
                    )
                })}
            </group>
        </>
    )
}

export default AisleInstances