import * as THREE from 'three';
import { Html } from '@react-three/drei';
import { useState, useEffect } from 'react';
import { useActiveLayer } from '../../../../store/store';

const ReferenceDistanceText = ({ line }: { line: any }) => {
    interface TextState {
        distance: string;
        position: THREE.Vector3;
        userData: any;
        layer: any;
    }

    const [text, setTexts] = useState<TextState | null>(null);
    const { activeLayer } = useActiveLayer();

    useEffect(() => {
        if (line) {
            if (line.parent === null) {
                setTexts(null);
                return;
            }
            const distance = line.userData.linePoints.cursorPosition.distanceTo(line.userData.linePoints.startPoint);
            const midpoint = new THREE.Vector3().addVectors(line.userData.linePoints.cursorPosition, line.userData.linePoints.startPoint).divideScalar(2);
            const newTexts = {
                distance: distance.toFixed(1),
                position: midpoint,
                userData: line,
                layer: activeLayer
            };
            setTexts(newTexts);
        }
    });

    return (
        <group name='Reference_Distance_Text'>
            <mesh>
                {text !== null &&
                    < Html transform sprite key={text.distance} userData={text.userData} scale={5} position={[text.position.x, 1, text.position.z]} style={{ pointerEvents: 'none' }}>
                        <div className={`Reference_Distance line-${text.userData.userData}`}>{text.distance} m</div>
                    </Html>
                }
            </mesh>
        </group >
    );
};

export default ReferenceDistanceText;