import React, { useRef, useEffect } from 'react';
import { GameState } from '../../types';
import { useGameStateContext } from '../../context/GameStateContext';
import Detection from '../Detection/Detection';
import Assignment from '../Assignment/Assignment';

const CameraScreen: React.FC = () => {
  const { 
    gameState, 
    setCurrentScreen, 
    setCameraStream, 
    scanTable,
    showResults
  } = useGameStateContext();
  
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const startCamera = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'environment' }
        });
        setCameraStream(stream);
        
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      } catch (err) {
        console.error('Camera access denied:', err);
        alert('Camera access denied. Please enable camera permissions.');
      }
    };

    startCamera();

    return () => {
      if (gameState.cameraStream) {
        gameState.cameraStream.getTracks().forEach(track => track.stop());
      }
    };
  }, []);

  const handleCardsDetected = (cards: any[]) => {
    scanTable(cards);
    showResults();
  };

  const scanTableHandler = async () => {
    if ((window as any).detectCards) {
      (window as any).detectCards();
    } else {
      // Fallback if the global detection function is not yet available
      const detectedCards = [
        {
          id: '1',
          suit: 'Schellen',
          value: 11,
          x: 100,
          y: 100,
          width: 40,
          height: 55,
          confidence: 0.85
        },
        {
          id: '2',
          suit: 'Schilten',
          value: 12,
          x: 200,
          y: 150,
          width: 40,
          height: 55,
          confidence: 0.78
        },
        {
          id: '3',
          suit: 'Eicheln',
          value: 10,
          x: 300,
          y: 200,
          width: 40,
          height: 55,
          confidence: 0.91
        }
      ];
      handleCardsDetected(detectedCards);
    }
  };

  return (
    <div className="screen camera-screen">
      <div className="camera-header">
        <h2>🎥 Round <span>{gameState.currentRound}</span></h2>
        <button onClick={() => gameState.setCurrentScreen('setup')} className="secondary">
          End Round
        </button>
      </div>
      
      <div className="camera-container">
        <video
          ref={videoRef}
          autoPlay
          playsInline
          muted
          className="camera-feed"
        />
        <canvas ref={canvasRef} className="hidden" />
        
        {/* Placeholder for radial sectors visualization */}
        {gameState.players.length > 0 && (
          <div className="radial-sectors">
            {gameState.players.map((player, index) => {
              const angle = (index * 2 * Math.PI) / gameState.players.length;
              const radius = 150;
              const x = 320 + radius * Math.cos(angle);
              const y = 240 + radius * Math.sin(angle);
              return (
                <div 
                  key={player.id} 
                  className="sector-label"
                  style={{ 
                    position: 'absolute', 
                    left: x - 20, 
                    top: y - 10,
                    transform: 'translate(-50%, -50%)'
                  }}
                >
                  {player.name}
                </div>
              );
            })}
          </div>
        )}
      </div>
      
      <div className="camera-status">
        Ready to scan. Tap "SCAN TABLE" when cards are arranged.
      </div>
      
      <div className="scan-button-container">
        <button 
          onClick={scanTableHandler} 
          className="scan-button"
        >
          SCAN TABLE
        </button>
      </div>
      
      {/* Detection component that handles actual detection logic */}
      <Detection 
        videoRef={videoRef} 
        canvasRef={canvasRef} 
        onCardsDetected={handleCardsDetected} 
      />
      
      {/* Assignment component that handles radial sector assignment */}
      {gameState.detectedCards.length > 0 && (
        <Assignment 
          players={gameState.players} 
          detectedCards={gameState.detectedCards} 
          onAssignedCards={(cards) => scanTable(cards)} 
        />
      )}
    </div>
  );
};

export default CameraScreen;