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

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

    const dashInstances = useMemo(() => {
        if (aisle.points.length < 2 || aisle.type.aisleType !== 'dashed-aisle') 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 dashLength = aisle.type.dashLength || 0.5;
        const gapLength = aisle.type.gapLength || 0.3;

        const totalVec = new THREE.Vector3().subVectors(end, start);
        const totalLength = totalVec.length();
        const direction = totalVec.clone().normalize();
        const segmentCount = Math.floor((totalLength + gapLength) / (dashLength + gapLength));

        const instances = [];

        for (let i = 0; i < segmentCount; i++) {
            const center = start.clone().addScaledVector(direction, i * (dashLength + gapLength) + dashLength / 2);

            const rotationY = Math.atan2(direction.x, direction.z);

            instances.push({
                position: [center.x, 0, center.z] as [number, number, number],
                scale: [width, 0.001, dashLength] as [number, number, number],
                rotation: [0, rotationY, 0] as [number, number, number],
            });
        }

        return instances;
    }, [aisle]);

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

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

    return (
        <group
            name="Dashed-Aisle"
            uuid={aisle.aisleUuid}
            ref={aisleRef}
            position={[0, (aisle.points[0].layer - 1) * Constants.wallConfig.height + 0.01, 0]}
            onDoubleClick={handleClick}
            onPointerMissed={() => {
                setSelectedAisle(null);
            }}
        >
            <Instances frustumCulled={false}>
                <boxGeometry args={[1, 1, 1]} />
                <meshStandardMaterial color={aisle.type.aisleColor || '#ffffff'} />
                {dashInstances.map((inst, i) => (
                    <Instance
                        key={i}
                        position={inst.position}
                        scale={inst.scale}
                        rotation={inst.rotation}
                    />
                ))}
            </Instances>
        </group>
    );
}

export default DashedAisle;
