import { OrbitControls } from "@react-three/drei";
import { Fragment, useEffect, useRef } from "react";
import { OrbitControls as OrbitControlsImpl } from "three-stdlib";
import useCompass from "../../store/useCompass";
import SphereTour from "./SphereTour";
import { IAppartmentComplex } from "../../types/apartmentSphere";
import useSphere from "../../store/useSphere";
import LabelMarker from "./LabelMarker";

interface VirtualTourWrapperProps {
  appartment: IAppartmentComplex;
}

const VirtualTourWrapper = ({ appartment }: VirtualTourWrapperProps) => {
  const orbitRef = useRef<OrbitControlsImpl>(null);

  const { setCurrentCompassRotate } = useCompass();
  const { selectedSphere, setSelectedSphere } = useSphere();

  const handleOnRotating = () => {
    const radian = orbitRef.current?.getAzimuthalAngle();
    if (radian) {
      const currentCompasDegrees = (radian * 180) / Math.PI + 180;
      setCurrentCompassRotate(currentCompasDegrees);
    }
  };

  useEffect(() => {
    setSelectedSphere(appartment.spheres[0]);
  }, [appartment.spheres, setSelectedSphere]);

  return (
    <>
      {appartment.spheres.map((sphere) => {
        const isLabelContains =
          selectedSphere && sphere.id === selectedSphere.id;

        return (
          <Fragment key={sphere.id}>
            {isLabelContains &&
              sphere.links.map((sphereLink) => (
                <LabelMarker
                  sphereLink={sphereLink}
                  apartment={appartment}
                  key={sphereLink.id}
                />
              ))}
            <SphereTour
              sphere={sphere}
              selectedSphere={
                selectedSphere ? selectedSphere : appartment.spheres[0]
              }
            />
          </Fragment>
        );
      })}
      <OrbitControls
        ref={orbitRef}
        maxDistance={0.001}
        enableZoom={false}
        rotateSpeed={0.5}
        reverseOrbit
        onChange={handleOnRotating}
        target={[
          appartment.spheres[0].position[0],
          appartment.spheres[0].position[1],
          appartment.spheres[0].position[2],
        ]}
      />
    </>
  );
};

export default VirtualTourWrapper;
