import * as THREE from 'three';
import { useMemo } from 'react';
import { Extrude } from '@react-three/drei';
import * as Constants from '../../../../../../types/world/worldConstants';

function DottedAisle({ aisle }: { readonly aisle: Aisle }) {
    const shapes = useMemo(() => {
        if (aisle.points.length < 2) return [];

        const start = new THREE.Vector3(...aisle.points[0].position);
        const end = new THREE.Vector3(...aisle.points[1].position);
        const width = aisle.type.aisleWidth || 0.1;
        const dotSpacing = 0.5;
        const dotRadius = width * 0.4;

        const totalLength = new THREE.Vector3().subVectors(end, start).length();
        const dotCount = Math.floor(totalLength / dotSpacing);

        const shapes = [];
        const directionNormalized = new THREE.Vector3().subVectors(end, start).normalize();

        for (let i = 0; i < dotCount; i++) {
            const dotCenter = new THREE.Vector3().copy(start).addScaledVector(directionNormalized, i * dotSpacing + dotSpacing / 2);

            const shape = new THREE.Shape();
            shape.absarc(dotCenter.x, dotCenter.z, dotRadius, 0, Math.PI * 2, false);

            shapes.push(shape);
        }

        return shapes;
    }, [aisle]);

    if (shapes.length === 0) return null;

    return (
        <group
            position={[0, (aisle.points[0].layer - 1) * Constants.wallConfig.height + 0.01, 0]}
            rotation={[Math.PI / 2, 0, 0]}
        >
            {shapes.map((shape, index) => (
                <Extrude
                    key={index}
                    args={[shape, { depth: 0.01, bevelEnabled: false }]}
                    receiveShadow
                    castShadow
                >
                    <meshStandardMaterial
                        color={aisle.type.aisleColor || '#ffffff'}
                        side={THREE.DoubleSide}
                    />
                </Extrude>
            ))}
        </group>
    );
}

export default DottedAisle;