import * as THREE from 'three';
import { useMemo, useRef } from 'react';
import { Instance, Instances } from '@react-three/drei';
import * as Constants from '../../../../../../types/world/worldConstants';
import { useToolMode } from '../../../../../../store/builder/store';
import { useBuilderStore } from '../../../../../../store/builder/useBuilderStore';

function DottedAisle({ aisle }: { readonly aisle: Aisle }) {
    const aisleRef = useRef<THREE.Group>(null);
    const { toolMode } = useToolMode();
    const { setSelectedAisle, hoveredPoint } = useBuilderStore();

    const dotPositions = useMemo(() => {
        if (aisle.points.length < 2 || aisle.type.aisleType !== 'dotted-aisle') return [];

        const start = new THREE.Vector3(...aisle.points[0].position);
        const end = new THREE.Vector3(...aisle.points[1].position);
        const dotSpacing = aisle.type.gapLength || 0.5;

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

        return Array.from({ length: dotCount }, (_, i) => {
            return new THREE.Vector3().copy(start).addScaledVector(directionNormalized, i * dotSpacing + dotSpacing / 2);
        });
    }, [aisle]);

    const handleClick = () => {
        if (toolMode === 'move' && !hoveredPoint) {
            setSelectedAisle(aisleRef.current);
        }
    }

    const { dotRadius, color } = useMemo(() => {
        return {
            dotRadius: aisle.type.aisleType === 'dotted-aisle' ? ((aisle.type as any).dotRadius || 0.1) * 0.6 : 0.06,
            color: aisle.type.aisleColor || '#ffffff'
        };
    }, [aisle]);

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

    return (
        <group
            name='Dotted-Aisle'
            uuid={aisle.aisleUuid}
            ref={aisleRef}
            position={[0, (aisle.points[0].layer - 1) * Constants.wallConfig.height + 0.01, 0]}
            userData={aisle}
            onDoubleClick={handleClick}
            onPointerMissed={() => {
                setSelectedAisle(null);
            }}
        >
            <Instances frustumCulled={false}>
                <circleGeometry args={[dotRadius, 32]} />
                <meshStandardMaterial color={color} side={THREE.DoubleSide} />
                {dotPositions.map((position, index) => (
                    <Instance
                        key={index}
                        position={[position.x, 0, position.z]}
                        rotation={[-Math.PI / 2, 0, 0]}
                    />
                ))}
            </Instances>
        </group>
    );
}

export default DottedAisle;