import React, { useEffect, useRef, useState } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, Environment, Effects } from '@react-three/drei';
import * as THREE from 'three';
import { WebTransportEngine } from '../../core/WebTransportEngine';

// Komponen 3D: Holographic Monolith untuk menampilkan Video Frame
function HolographicMonolith({ frameQueue, position }) {
  const meshRef = useRef();
  const materialRef = useRef();
  const [videoTexture, setVideoTexture] = useState(null);
  const canvasRef = useRef(document.createElement('canvas'));
  const ctxRef = useRef(null);

  useEffect(() => {
    // Inisialisasi kanvas internal 2D untuk menerima VideoFrame (WebCodecs)
    canvasRef.current.width = 1280;
    canvasRef.current.height = 720;
    ctxRef.current = canvasRef.current.getContext('2d');
    
    // Buat Three.js Texture dari kanvas
    const tex = new THREE.CanvasTexture(canvasRef.current);
    tex.colorSpace = THREE.SRGBColorSpace;
    setVideoTexture(tex);

    return () => {
      tex.dispose();
    };
  }, []);

  useFrame((state, delta) => {
    if (meshRef.current) {
      // Rotasi perlahan ala Sci-Fi
      meshRef.current.rotation.y += delta * 0.1;
      // Melayang (hover effect)
      meshRef.current.position.y = position[1] + Math.sin(state.clock.elapsedTime) * 0.2;
    }

    // Ekstrak frame dari antrean (jika ada) dan lukis ke kanvas
    if (frameQueue.current && frameQueue.current.length > 0) {
      const frame = frameQueue.current.shift();
      if (ctxRef.current && videoTexture) {
        ctxRef.current.drawImage(frame, 0, 0, 1280, 720);
        videoTexture.needsUpdate = true;
      }
      frame.close(); // PENTING: Mencegah kebocoran memori (memory leak) di WebCodecs
    }
  });

  return (
    <mesh ref={meshRef} position={position}>
      {/* Bentuk Monolith: Lebar, Tinggi, Kedalaman */}
      <boxGeometry args={[3.2, 1.8, 0.1]} />
      <meshStandardMaterial 
        ref={materialRef}
        map={videoTexture}
        emissive={new THREE.Color(0x00f3ff)}
        emissiveMap={videoTexture}
        emissiveIntensity={0.5}
        transparent={true}
        opacity={0.9}
        roughness={0.1}
        metalness={0.8}
      />
    </mesh>
  );
}

export default function M15QuicVideoMatrix() {
  const [engineStatus, setEngineStatus] = useState('OFFLINE');
  const [activeCodec, setActiveCodec] = useState('PROBING HARDWARE...');
  const frameQueueRef = useRef([]);
  const engineRef = useRef(null);

  useEffect(() => {
    setEngineStatus('BOOTING WEBTRA-QUIC...');
    
    // Inisialisasi Mesin Kustom
    engineRef.current = new WebTransportEngine(
      (decodedFrame) => {
        // Masukkan frame hasil dekode ke antrean
        frameQueueRef.current.push(decodedFrame);
        // Cegah tumpukan frame jika tab tidak fokus
        if (frameQueueRef.current.length > 5) {
          const dropped = frameQueueRef.current.shift();
          dropped.close();
        }
      },
      (codecName) => {
        setActiveCodec(codecName);
      }
    );

    engineRef.current.initialize().then(success => {
      if (success) {
        setEngineStatus('QUIC DATAGRAM SYNCED (ZERO-LATENCY)');
      } else {
        setEngineStatus('HARDWARE ENCODER FAILED');
      }
    });

    return () => {
      if (engineRef.current) {
        engineRef.current.shutdown();
      }
      // Bersihkan sisa frame
      while (frameQueueRef.current.length > 0) {
        const frame = frameQueueRef.current.shift();
        frame.close();
      }
    };
  }, []);

  return (
    <div style={{animation: 'fadeIn 0.5s ease-out', height: '100%', display: 'flex', flexDirection: 'column'}}>
      
      {/* UI Overlay */}
      <div className="glass-panel" style={{
        padding: '15px', marginBottom: '15px', display: 'flex', justifyContent: 'space-between', 
        alignItems: 'center', borderColor: 'var(--accent-cyan)'
      }}>
        <div>
          <h2 style={{margin: 0, color: 'var(--accent-cyan)', letterSpacing: '2px', textTransform: 'uppercase'}}>M15: Neural WebTransport Matrix</h2>
          <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginTop: '5px'}}>
            Bypassing WebRTC. Hardware Encoders Only. Pure QUIC Datagrams.
          </div>
        </div>
        <div style={{textAlign: 'right'}}>
          <div style={{color: '#888', fontSize: '0.7rem', letterSpacing: '2px'}}>TRANSPORT STATUS</div>
          <div style={{color: engineStatus.includes('SYNCED') ? 'var(--accent-green)' : 'var(--accent-yellow)', fontWeight: 'bold', fontFamily: 'monospace'}}>
            {engineStatus}
          </div>
        </div>
      </div>

      {/* 3D WebGL Spatial Environment */}
      <div style={{flex: 1, borderRadius: '8px', overflow: 'hidden', border: '1px solid #333', background: '#000', position: 'relative'}}>
        
        {/* Holographic grid UI overlay over the 3D canvas */}
        <div style={{
          position: 'absolute', top: '20px', left: '20px', zIndex: 10,
          background: 'rgba(0, 243, 255, 0.1)', padding: '10px', borderLeft: '2px solid var(--accent-cyan)',
          fontFamily: 'monospace', fontSize: '0.8rem', color: 'var(--accent-cyan)', pointerEvents: 'none'
        }}>
          <div>DATAGRAM RATE: 3000 PKT/S</div>
          <div>ENCODER: {activeCodec}</div>
          <div>JITTER BUFFER: 0ms</div>
        </div>

        <Canvas camera={{ position: [0, 0, 5], fov: 60 }}>
          <ambientLight intensity={0.5} />
          <pointLight position={[10, 10, 10]} intensity={1} color="#00f3ff" />
          <pointLight position={[-10, -10, -10]} intensity={0.5} color="#a855f7" />
          
          <HolographicMonolith frameQueue={frameQueueRef} position={[0, 0, 0]} />
          
          <OrbitControls 
            enablePan={false} 
            maxPolarAngle={Math.PI / 1.5} 
            minPolarAngle={Math.PI / 3}
            autoRotate={false} 
          />
        </Canvas>
      </div>

    </div>
  );
}
