import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import panormaImage from '../assets/panoramas/cedar_bridge_sunset.jpg';
import panormaImage2 from '../assets/panoramas/cayley_interior.jpg';

interface VirtualTour360Props {
  isOpen: boolean;
  onClose: () => void;
  onBookNow?: () => void;
}

// Your 360° panorama images
const tourScenes = [
  {
    id: 0,
    title: "Cedar Bridge Sunset",
    capacity: "Outdoor Learning Space",
    description: "A serene outdoor setting with stunning sunset views, perfect for meditation and reflection sessions at Kautilya Leadership Centre.",
    features: ["Natural environment", "Sunset views", "Peaceful atmosphere", "Meditation area", "Reflection space"],
    panoramaUrl: panormaImage
  },
  {
    id: 1,
    title: "Training Amphitheater",
    capacity: "80-120 attendees",
    description: "State-of-the-art amphitheater with tiered seating, advanced acoustics, and immersive presentation technology.",
    features: ["Tiered seating", "4K projection", "Live streaming", "Acoustic panels"],
    panoramaUrl: panormaImage2
  },
];

export function VirtualTour360({ isOpen, onClose, onBookNow }: VirtualTour360Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [currentSceneIndex, setCurrentSceneIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  
  // Three.js refs
  const sceneRef = useRef<THREE.Scene | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const controlsRef = useRef<OrbitControls | null>(null);
  const currentMeshRef = useRef<THREE.Mesh | null>(null);
  const currentTextureRef = useRef<THREE.Texture | null>(null);
  const animationRef = useRef<number | null>(null);

  // Initialize Three.js scene
  useEffect(() => {
    if (!isOpen || !containerRef.current) return;

    const container = containerRef.current;

    // Setup scene
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x050510);
    sceneRef.current = scene;

    // Setup camera
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 0, 0.1);
    cameraRef.current = camera;

    // Setup renderer
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.domElement.style.touchAction = "none"; // Important for touch events
    container.appendChild(renderer.domElement);
    rendererRef.current = renderer;

    // Setup controls - ONLY ROTATION (no built-in zoom)
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableZoom = false; // Disable built-in zoom, we'll handle custom zoom
    controls.enablePan = false;
    controls.enableRotate = true;
    controls.rotateSpeed = 1.2;
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.target.set(0, 0, 0);
    controlsRef.current = controls;

    // 🔥 CUSTOM ZOOM - Mouse wheel (desktop)
    const handleWheel = (event: WheelEvent) => {
      if (!cameraRef.current) return;
      
      event.preventDefault();
      
      const zoomSpeed = 0.05;
      cameraRef.current.fov += event.deltaY * zoomSpeed;
      
      // Limit zoom range
      cameraRef.current.fov = Math.max(40, Math.min(90, cameraRef.current.fov));
      cameraRef.current.updateProjectionMatrix();
    };
    
    renderer.domElement.addEventListener("wheel", handleWheel, { passive: false });

    // 🔥 CUSTOM ZOOM - Mobile pinch gesture
    let lastDistance = 0;
    
    const getDistance = (touches: TouchList) => {
      if (touches.length < 2) return 0;
      const dx = touches[0].clientX - touches[1].clientX;
      const dy = touches[0].clientY - touches[1].clientY;
      return Math.sqrt(dx * dx + dy * dy);
    };
    
    const handleTouchMove = (e: TouchEvent) => {
      if (!cameraRef.current) return;
      
      if (e.touches.length === 2) {
        e.preventDefault();
        
        const distance = getDistance(e.touches);
        
        if (lastDistance > 0) {
          const delta = distance - lastDistance;
          cameraRef.current.fov -= delta * 0.05;
          cameraRef.current.fov = Math.max(40, Math.min(90, cameraRef.current.fov));
          cameraRef.current.updateProjectionMatrix();
        }
        
        lastDistance = distance;
      }
    };
    
    const handleTouchEnd = () => {
      lastDistance = 0;
    };
    
    renderer.domElement.addEventListener("touchmove", handleTouchMove, { passive: false });
    renderer.domElement.addEventListener("touchend", handleTouchEnd);

    // Animation loop
    const animate = () => {
      animationRef.current = requestAnimationFrame(animate);
      
      if (controlsRef.current) controlsRef.current.update();
      if (rendererRef.current && sceneRef.current && cameraRef.current) {
        rendererRef.current.render(sceneRef.current, cameraRef.current);
      }
    };
    animate();

    // Load first panorama
    loadPanorama(tourScenes[0].panoramaUrl);

    // Handle window resize
    const handleResize = () => {
      if (cameraRef.current && rendererRef.current) {
        cameraRef.current.aspect = window.innerWidth / window.innerHeight;
        cameraRef.current.updateProjectionMatrix();
        rendererRef.current.setSize(window.innerWidth, window.innerHeight);
      }
    };
    window.addEventListener('resize', handleResize);

    // Cleanup
    return () => {
      if (animationRef.current) cancelAnimationFrame(animationRef.current);
      
      window.removeEventListener('resize', handleResize);
      renderer.domElement.removeEventListener("wheel", handleWheel);
      renderer.domElement.removeEventListener("touchmove", handleTouchMove);
      renderer.domElement.removeEventListener("touchend", handleTouchEnd);
      
      if (controlsRef.current) controlsRef.current.dispose();
      if (rendererRef.current) rendererRef.current.dispose();
      if (currentTextureRef.current) currentTextureRef.current.dispose();
      
      if (container && renderer.domElement && container.contains(renderer.domElement)) {
        container.removeChild(renderer.domElement);
      }
    };
  }, [isOpen]);

  // Load panorama image
  const loadPanorama = (imageUrl: string) => {
    if (!sceneRef.current) return;
    
    setIsLoading(true);
    
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load(
      imageUrl,
      (texture) => {
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.ClampToEdgeWrapping;
        texture.colorSpace = THREE.SRGBColorSpace;
        
        // Remove old mesh
        if (currentMeshRef.current) sceneRef.current?.remove(currentMeshRef.current);
        if (currentTextureRef.current) currentTextureRef.current.dispose();
        
        // Create new sphere with texture
        const geometry = new THREE.SphereGeometry(500, 64, 64);
        const material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.BackSide });
        const sphere = new THREE.Mesh(geometry, material);
        sceneRef.current?.add(sphere);
        
        currentMeshRef.current = sphere;
        currentTextureRef.current = texture;
        
        // Reset camera FOV when loading new scene
        if (cameraRef.current) {
          cameraRef.current.fov = 75;
          cameraRef.current.updateProjectionMatrix();
        }
        
        setIsLoading(false);
      },
      undefined,
      (error) => {
        console.error('Error loading panorama:', error);
        setIsLoading(false);
      }
    );
  };

  // Navigate to next scene
  const nextScene = () => {
    const nextIndex = (currentSceneIndex + 1) % tourScenes.length;
    setCurrentSceneIndex(nextIndex);
    loadPanorama(tourScenes[nextIndex].panoramaUrl);
  };

  // Navigate to previous scene
  const prevScene = () => {
    const prevIndex = (currentSceneIndex - 1 + tourScenes.length) % tourScenes.length;
    setCurrentSceneIndex(prevIndex);
    loadPanorama(tourScenes[prevIndex].panoramaUrl);
  };

  // Jump to specific scene
  const goToScene = (index: number) => {
    setCurrentSceneIndex(index);
    loadPanorama(tourScenes[index].panoramaUrl);
  };

  const currentScene = tourScenes[currentSceneIndex];

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] bg-black">
      {/* Canvas container for Three.js */}
      <div ref={containerRef} className="absolute inset-0" />
      
      {/* UI Overlay */}
      <div className="absolute inset-0 pointer-events-none">
        {/* Top Bar */}
        <div className="absolute top-0 left-0 right-0 bg-gradient-to-r from-[#04045B]/95 to-[#04045B]/80 backdrop-blur-md border-b border-yellow-400/30 pointer-events-auto z-30">
          <div className="flex justify-between items-center px-4 md:px-6 py-3 md:py-4">
            <div className="flex items-center gap-2 md:gap-3">
              <div className="w-8 h-8 md:w-10 md:h-10 bg-yellow-400 rounded-xl flex items-center justify-center font-bold text-[#04045B] text-base md:text-xl">
                KL
              </div>
              <div className="hidden sm:block">
                <h1 className="text-white font-semibold text-sm md:text-lg">Kautilya Leadership Centre</h1>
                <p className="text-white/70 text-xs">360° Immersive Experience</p>
              </div>
            </div>
            
            <div className="flex items-center gap-2 md:gap-3">
              <button
                onClick={prevScene}
                className="w-8 h-8 md:w-9 md:h-9 rounded-full bg-white/20 hover:bg-yellow-400 hover:text-[#04045B] transition-all flex items-center justify-center text-white text-sm md:text-base touch-manipulation"
                aria-label="Previous scene"
              >
                ◀
              </button>
              <div className="bg-black/50 backdrop-blur-sm px-3 py-1.5 md:px-4 rounded-full text-xs md:text-sm font-medium">
                {currentScene.title}
              </div>
              <button
                onClick={nextScene}
                className="w-8 h-8 md:w-9 md:h-9 rounded-full bg-white/20 hover:bg-yellow-400 hover:text-[#04045B] transition-all flex items-center justify-center text-white text-sm md:text-base touch-manipulation"
                aria-label="Next scene"
              >
                ▶
              </button>
              <button
                onClick={onClose}
                className="w-8 h-8 md:w-9 md:h-9 rounded-full bg-white/20 hover:bg-red-500 transition-all flex items-center justify-center text-white text-sm md:text-base touch-manipulation"
                aria-label="Close"
              >
                ✕
              </button>
            </div>
          </div>
        </div>

        {/* Info Panel - Bottom Left */}
        <div className="absolute bottom-4 md:bottom-6 left-4 md:left-6 max-w-[280px] md:max-w-[320px] bg-[#04045B]/90 backdrop-blur-md rounded-xl md:rounded-2xl p-4 md:p-5 border border-yellow-400/40 pointer-events-auto z-25">
          <h2 className="text-yellow-400 text-lg md:text-2xl font-bold mb-1">{currentScene.title}</h2>
          <div className="text-white/80 text-xs md:text-sm mb-2 md:mb-3 flex items-center gap-2">
            🎯 Capacity: {currentScene.capacity}
          </div>
          <p className="text-white/90 text-xs md:text-sm mb-3 md:mb-4 leading-relaxed">
            {currentScene.description}
          </p>
          <div className="flex flex-wrap gap-1.5 md:gap-2 mb-3 md:mb-4">
            {currentScene.features.map((feature, idx) => (
              <span key={idx} className="bg-yellow-400/20 text-yellow-400 text-[10px] md:text-xs px-2 py-1 md:px-3 rounded-full">
                ✓ {feature}
              </span>
            ))}
          </div>
          <button
            onClick={() => {
              onBookNow?.();
              onClose();
            }}
            className="w-full bg-yellow-400 hover:bg-yellow-500 text-[#04045B] font-bold py-2 md:py-2.5 rounded-full transition-all flex items-center justify-center gap-2 text-sm md:text-base touch-manipulation"
          >
            📅 Book This Space →
          </button>
        </div>

        {/* Scene Thumbnails - Bottom Right */}
        <div className="absolute bottom-4 md:bottom-6 right-4 md:right-6 flex flex-col gap-2 pointer-events-auto z-25">
          {tourScenes.map((scene, idx) => (
            <button
              key={scene.id}
              onClick={() => goToScene(idx)}
              className={`bg-black/70 backdrop-blur-sm rounded-full px-3 py-1.5 md:px-4 md:py-2 flex items-center gap-2 md:gap-3 hover:bg-[#04045B]/90 transition-all touch-manipulation ${
                idx === currentSceneIndex ? 'border-l-4 border-yellow-400' : 'border-l-4 border-yellow-400/40'
              }`}
            >
              <div className="w-1.5 h-1.5 md:w-2 md:h-2 bg-yellow-400 rounded-full" />
              <span className="text-white text-[10px] md:text-xs font-medium truncate max-w-[120px] md:max-w-[150px]">
                {scene.title}
              </span>
            </button>
          ))}
        </div>

        {/* Loading Overlay */}
        {isLoading && (
          <div className="absolute inset-0 bg-[#04045B] flex items-center justify-center z-50">
            <div className="text-center">
              <div className="w-12 h-12 border-4 border-yellow-400/30 border-t-yellow-400 rounded-full animate-spin mx-auto mb-4"></div>
              <p className="text-white text-sm">Loading 360° Experience...</p>
            </div>
          </div>
        )}

        {/* Instruction Hint */}
        <div className="absolute bottom-4 md:bottom-6 left-1/2 transform -translate-x-1/2 bg-black/60 backdrop-blur-sm rounded-full px-3 py-1.5 md:px-4 md:py-2 text-white text-[10px] md:text-xs pointer-events-auto whitespace-nowrap">
          🖱️ Drag to look around • 👆 Pinch/Scroll to zoom in/out
        </div>
      </div>
    </div>
  );
}