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
            // data
            key={text.distance}
            userData={text.userData}
            position={[text.position.x, 1, text.position.z]}
            // class
            wrapperClass="distance-text-wrapper"
            className="distance-text"
            // other
            zIndexRange={[1, 0]}
            prepend
            sprite
          >
            <div
              className={`Reference_Distance line-${text.userData.userData}`}
            >
              {text.distance} m
            </div>
          </Html>
        )}
      </mesh>
    </group>
  );
};

export default ReferenceDistanceText;
