import React, { useContext, useEffect, useRef } from 'react';
import { OrbitControls } from '@react-three/drei';
import { useThree } from '@react-three/fiber';
import { useViewerStore } from '@/store/viewerStore';
import { ViewerModuleContext } from '../SceneCanvas';

type OrbitControlsProps = React.ComponentProps<typeof OrbitControls>;

export const ViewerOrbitControls: React.FC<OrbitControlsProps> = (props) => {
  const moduleId = useContext(ViewerModuleContext);
  const { locks, cameras, saveCamera } = useViewerStore();
  const { camera } = useThree();
  const controlsRef = useRef<any>(null);
  
  const isLocked = moduleId ? !!locks[moduleId] : false;

  // Carrega a posição salva da câmera se existir
  useEffect(() => {
    if (moduleId && cameras[moduleId] && controlsRef.current) {
      const saved = cameras[moduleId];
      camera.position.set(saved.position[0], saved.position[1], saved.position[2]);
      controlsRef.current.target.set(saved.target[0], saved.target[1], saved.target[2]);
      controlsRef.current.update();
    }
  }, [moduleId, camera]); // executado uma vez por módulo

  const handleEnd = () => {
    if (moduleId && controlsRef.current) {
      saveCamera(moduleId, {
        position: [camera.position.x, camera.position.y, camera.position.z],
        target: [
          controlsRef.current.target.x,
          controlsRef.current.target.y,
          controlsRef.current.target.z
        ]
      });
    }
    if (props.onEnd) {
      props.onEnd(undefined as any);
    }
  };

  return (
    <OrbitControls
      ref={controlsRef}
      enabled={!isLocked}
      onEnd={handleEnd}
      {...props}
    />
  );
};
