import { Html } from "@react-three/drei";
import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes";
import { useDrieTemp, useDrieUIValue } from "../../../store/store"
import UI from "./ui";
import { useEffect } from "react";
import { useThree } from "@react-three/fiber";

export default function DrieHtmlTemp({ itemsGroup }: { itemsGroup: Types.RefGroup }) {
  const { drieTemp, setDrieTemp } = useDrieTemp();
  const { drieUIValue, setDrieUIValue } = useDrieUIValue();
  const state = useThree();
  const { camera, raycaster } = state;

  useEffect(() => {
    const canvasElement = state.gl.domElement;
    let drag = false;
    let isLeftMouseDown = false;

    const onMouseDown = (evt: any) => {
      if (evt.button === 0) {
        isLeftMouseDown = true;
        drag = false;
      }
    };

    const onMouseMove = () => {
      if (isLeftMouseDown) {
        drag = true;
      }
    };

    const onMouseUp = (evt: any) => {
      if (evt.button === 0) {
        isLeftMouseDown = false;
        if (drag) return;
        if (!itemsGroup.current) return
        let intersects = raycaster.intersectObjects(itemsGroup.current.children, true);
        if (intersects.length > 0) {
          let currentObject = intersects[0].object;

          while (currentObject) {
            if (currentObject.name === "Scene") {
              break;
            }
            currentObject = currentObject.parent as THREE.Object3D;
          }
          if (currentObject && (currentObject.userData.name === "SV2 Controll pannel" || currentObject.userData.name === "forklift")) {
            const worldPos = new THREE.Vector3();
            currentObject.getWorldPosition(worldPos);

            const rightOffset = new THREE.Vector3(1, 0, 0);
            const upOffset = new THREE.Vector3(0, 1, 0);

            currentObject.localToWorld(rightOffset);
            currentObject.localToWorld(upOffset);

            const finalPosition = worldPos.clone().addScaledVector(rightOffset.sub(currentObject.position).normalize(), 2.5).addScaledVector(upOffset.sub(currentObject.position).normalize(), 2.3);

            setDrieTemp(finalPosition);
          } else {
            setDrieTemp(undefined);
          }
        }
        else {
          setDrieTemp(undefined);
        }
      }
    };


    canvasElement.addEventListener("mousedown", onMouseDown);
    canvasElement.addEventListener("mouseup", onMouseUp);
    canvasElement.addEventListener("mousemove", onMouseMove);

    return () => {
      canvasElement.removeEventListener("mousedown", onMouseDown);
      canvasElement.removeEventListener("mouseup", onMouseUp);
      canvasElement.removeEventListener("mousemove", onMouseMove);
    };
  }, [])

  return (
    <>
      {drieTemp &&
        <mesh position={[drieTemp.x, drieTemp.y, drieTemp.z]}>
          <Html
            as="div"
            center
            zIndexRange={[1, 0]}
            transform
            sprite
            style={{
              padding: "10px",
              color: "white",
              borderRadius: "8px",
              textAlign: "center",
              fontFamily: "Arial, sans-serif",
            }}
            scale={[0.3, 0.3, 0.3]}
          // occlude
          >
            <UI temperature={drieUIValue.temperature} humidity={drieUIValue.humidity} touch={drieUIValue.touch} header={""} />
          </Html>
        </mesh>
      }
    </>
  )
}