import React, { useRef, useEffect } from 'react';
import { Card } from '../../types';
import { DetectionPipeline } from './DetectionLogic';

interface DetectionProps {
  videoRef: React.RefObject<HTMLVideoElement>;
  canvasRef: React.RefObject<HTMLCanvasElement>;
  onCardsDetected: (cards: Card[]) => void;
  live?: boolean;
  onLiveCardsDetected?: (cards: Card[]) => void;
}

const Detection: React.FC<DetectionProps> = ({ videoRef, canvasRef, onCardsDetected, live, onLiveCardsDetected }) => {
  const isDetectingRef = useRef(false);
  const requestRef = useRef<number>();
  const pipelineRef = useRef(new DetectionPipeline());

  const detectCards = async () => {
    if (!videoRef.current || !canvasRef.current || isDetectingRef.current) return;
    
    isDetectingRef.current = true;
    
    try {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      
      if (!ctx) return;
      
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      const detectedCards = await pipelineRef.current.processImageForCards(canvas, ctx);
      
      onCardsDetected(detectedCards);
    } catch (error) {
      console.error('Card detection failed:', error);
      onCardsDetected([]);
    } finally {
      isDetectingRef.current = false;
    }
  };

  const runLiveDetection = async () => {
    if (!videoRef.current || !canvasRef.current || isDetectingRef.current) return;
    
    isDetectingRef.current = true;
    
    try {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      
      if (!ctx) return;
      
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      const detectedCards = await pipelineRef.current.processImageForCards(canvas, ctx);
      
      if (onLiveCardsDetected) {
        onLiveCardsDetected(detectedCards);
      }
    } catch (error) {
      console.error('Live detection failed:', error);
    } finally {
      isDetectingRef.current = false;
    }
  };

  useEffect(() => {
    if (live) {
      const loop = async () => {
        await runLiveDetection();
        requestRef.current = requestAnimationFrame(loop);
      };
      requestRef.current = requestAnimationFrame(loop);
      return () => {
        if (requestRef.current) {
          cancelAnimationFrame(requestRef.current);
        }
      };
    }
  }, [live]);

  useEffect(() => {
    (window as any).detectCards = detectCards;
  }, []);

  return null;
};

export default Detection;
