import { Canvas, useThree } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { useEffect, useState, useRef } from 'react';
import { DuckModel } from './DuckModel';
import { DebugPanel } from './DebugPanel';

type CameraInfoProps = {
  onUpdate: (info: { cameraPosition: number[]; target: number[]; zoom: number }) => void;
  initialTarget: [number, number, number];
  fullControlMode: boolean;
  initialPosition: [number, number, number];
};

function CameraInfo({ onUpdate, initialTarget, fullControlMode, initialPosition }: CameraInfoProps) {
  const { camera } = useThree();
  const controlsRef = useRef<any>(null);

  useEffect(() => {
    if (controlsRef.current) {
      controlsRef.current.target.set(...initialTarget);
      camera.position.set(...initialPosition);
      controlsRef.current.update();
    }
  }, [initialTarget, initialPosition, camera]);

  useEffect(() => {
    const interval = setInterval(() => {
      if (controlsRef.current) {
        const controls = controlsRef.current;
        onUpdate({
          cameraPosition: camera.position.toArray(),
          target: controls.target.toArray(),
          zoom: camera.zoom,
        });
      }
    }, 100);

    return () => clearInterval(interval);
  }, [camera, onUpdate]);

  return (
    <OrbitControls
      ref={controlsRef}
      enabled={fullControlMode}
      enableRotate={fullControlMode}
      enableZoom={fullControlMode}
      enablePan={fullControlMode}
      target={initialTarget}
    />
  );
}

type DuckAvatarProps = {
  showDebug: boolean;
  fullControlMode: boolean;
  currentSection: number;
};

export function DuckAvatar({ showDebug, fullControlMode, currentSection }: DuckAvatarProps) {
  const isHeroSection = currentSection === 0;
  const [cameraInfo, setCameraInfo] = useState({
    cameraPosition: [2.89, 5.24, 7.38],
    target: [0.3, 3.29, -0.4],
    zoom: 1,
  });

  const [modelInfo, setModelInfo] = useState({
    position: [0, -0.2, 0],
    rotation: [-0.1, -0.75, 0],
    scale: 4.5,
  });

  const [isLoaded, setIsLoaded] = useState(false);

  const heroClasses = 'fixed top-12 md:top-auto md:bottom-0 left-1/2 -translate-x-1/2 w-[60vh] h-[75vh]';
  const miniClasses = 'fixed bottom-4 right-4 w-[20vh] h-[25vh]';

  return (
    <div
      className={`${isHeroSection ? heroClasses : miniClasses} overflow-visible z-1 pointer-events-none`}
      style={{
        background: 'transparent',
        opacity: isLoaded ? 1 : 0,
      }}
    >
      <div className="w-full h-full pointer-events-none overflow-visible" style={{ background: 'transparent' }}>
        <Canvas
          camera={{
            position: [2.89, 5.24, 7.38],
            fov: 65,
            near: 0.1,
            far: 1000,
          }}
          style={{ background: 'transparent' }}
        >
          <ambientLight intensity={1.5} />
          <directionalLight position={[10, 10, 5]} intensity={2} />
          <directionalLight position={[-10, -10, -5]} intensity={1} />
          <pointLight position={[0, 5, 0]} intensity={1.5} />
          <CameraInfo
            onUpdate={setCameraInfo}
            initialTarget={[0.3, 3.29, -0.4]}
            fullControlMode={fullControlMode}
            initialPosition={[2.89, 5.24, 7.38]}
          />
          <DuckModel
            onUpdate={setModelInfo}
            onAssetsLoaded={() => {
              setIsLoaded(true);
            }}
            currentSection={currentSection}
          />
        </Canvas>
      </div>
      {showDebug && <DebugPanel fullControlMode={fullControlMode} cameraInfo={cameraInfo} modelInfo={modelInfo} />}
    </div>
  );
}
