import { useCallback } from 'react';
import { useAisleStore } from '../../../../store/builder/useAisleStore';
import * as THREE from 'three';

const SNAP_THRESHOLD = 0.5; // Distance threshold for snapping in meters

const CAN_SNAP = true; // Whether snapping is enabled or not

export const usePointSnapping = (currentPoint: { uuid: string, pointType: string, position: [number, number, number] } | null) => {
    const { aisles } = useAisleStore();

    const getAllOtherPoints = useCallback(() => {
        if (!currentPoint) return [];

        return aisles.flatMap(aisle =>
            aisle.points.filter(point => point.pointUuid !== currentPoint.uuid)
        );
    }, [aisles, currentPoint]);

    const checkSnapForAisle = useCallback((position: [number, number, number]) => {
        if (!currentPoint || !CAN_SNAP) return { position: position, isSnapped: false, snappedPoint: null };

        const otherPoints = getAllOtherPoints();
        const currentVec = new THREE.Vector3(...position);

        for (const point of otherPoints) {
            const pointVec = new THREE.Vector3(...point.position);
            const distance = currentVec.distanceTo(pointVec);

            if (distance <= SNAP_THRESHOLD && currentPoint.pointType === 'Aisle') {
                return { position: point.position, isSnapped: true, snappedPoint: point };
            }
        }

        return { position: position, isSnapped: false, snappedPoint: null };
    }, [currentPoint, getAllOtherPoints]);

    return {
        checkSnapForAisle,
    };
};