'use client';

import { useEffect, useRef, useState } from 'react';
import { pusherClient } from '@/lib/pusher';

export default function LiveCam() {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const countdownRef = useRef<NodeJS.Timeout | null>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [sessionId, setSessionId] = useState<string>('');
  const [error, setError] = useState<string>('');
  const [capturedPhoto, setCapturedPhoto] = useState<string>('');
  const [countdown, setCountdown] = useState<number | null>(null);
  const [isBlinking, setIsBlinking] = useState(false);
  const [isCapturing, setIsCapturing] = useState(false);
  const [photoCount, setPhotoCount] = useState(0);
  const captureInProgressRef = useRef(false);
  const inactivityTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const MAX_CAPTURES = parseInt(process.env.NEXT_PUBLIC_MAX_CAPTURES || '3');
  const INACTIVITY_TIMEOUT = 3 * 60 * 1000; // 3 minutes
  const CAMERA_ORIENTATION = process.env.NEXT_PUBLIC_CAMERA_ORIENTATION || 'landscape';

  const loadPhotoCount = async (id: string) => {
    try {
      const response = await fetch(`/api/photos/${id}`);
      const data = await response.json();
      const currentPhotoCount = data.photos ? data.photos.length : 0;
      setPhotoCount(currentPhotoCount);
      return currentPhotoCount;
    } catch (error) {
      console.error('Error loading photo count:', error);
      setPhotoCount(0);
      return 0;
    }
  };

  const resetInactivityTimeout = () => {
    if (inactivityTimeoutRef.current) {
      clearTimeout(inactivityTimeoutRef.current);
    }
    
    inactivityTimeoutRef.current = setTimeout(() => {
      console.log('Inactivity timeout reached, redirecting to QR');
      window.location.href = '/qr';
    }, INACTIVITY_TIMEOUT);
  };

  const checkAndRedirectIfComplete = (currentCount: number) => {
    if (currentCount >= MAX_CAPTURES) {
      console.log('Maximum captures reached, redirecting to QR');
      setTimeout(() => {
        window.location.href = '/qr';
      }, 2000);
    }
  };

  const startCamera = async () => {
    try {
      setError('');
      
      // Set video constraints based on orientation
      const isPortrait = CAMERA_ORIENTATION.toLowerCase() === 'portrait';
      const videoConstraints = {
        video: {
          width: isPortrait ? { ideal: 720 } : { ideal: 1280 },
          height: isPortrait ? { ideal: 1280 } : { ideal: 720 },
          aspectRatio: isPortrait ? 9/16 : 16/9,
          facingMode: 'user' // front camera (for selfies)
        },
        audio: false
      };

      const mediaStream = await navigator.mediaDevices.getUserMedia(videoConstraints);

      setStream(mediaStream);
      
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
        videoRef.current.play();
      }
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      setError(`Error: ${errorMessage}`);
      console.error('Camera error:', err);
    }
  };

  const startCountdown = () => {
    // Prevent multiple countdowns running simultaneously
    if (countdown !== null || isCapturing || countdownRef.current) {
      console.log('BLOCKED: Already processing', { countdown, isCapturing, hasTimer: !!countdownRef.current });
      return;
    }

    console.log('STARTING countdown');
    setCountdown(3);
    setIsCapturing(true);
    
    const countdownInterval = setInterval(() => {
      setCountdown((prev) => {
        if (prev === null) return null;
        
        const nextValue = prev - 1;
        
        if (nextValue <= 0) {
          clearInterval(countdownInterval);
          countdownRef.current = null;
          
          // After countdown, capture photo and trigger blinking
          setTimeout(async () => {
            await capturePhotoActual();
            triggerBlinking();
            setIsCapturing(false);
          }, 100);
          return null;
        }
        
        return nextValue;
      });
    }, 1000);
    
    countdownRef.current = countdownInterval;
  };

  const triggerBlinking = () => {
    setIsBlinking(true);
    setTimeout(() => {
      setIsBlinking(false);
    }, 300);
  };

  const capturePhotoActual = async () => {
    console.log('CAPTURE PHOTO CALLED');
    
    // Prevent duplicate photo capture
    if (captureInProgressRef.current) {
      console.log('CAPTURE BLOCKED: Already in progress');
      return;
    }
    
    captureInProgressRef.current = true;
    console.log('CAPTURE PROCEEDING');
    
    // Get session ID directly from URL to avoid closure issues
    const urlParams = new URLSearchParams(window.location.search);
    const currentSessionId = urlParams.get('id') || '';
    
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');

      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      if (context) {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const photoDataUrl = canvas.toDataURL('image/jpeg', 0.8);
        setCapturedPhoto(photoDataUrl);

        // Save photo to server and send via Pusher if sessionId exists
        if (currentSessionId) {
          try {
            await fetch('/api/save-photo', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ 
                sessionId: currentSessionId, 
                photoDataUrl 
              }),
            });
          } catch (error) {
            console.error('Error saving photo:', error);
          }
        }
      }
    }
    
    // Reset flag after capture is complete
    captureInProgressRef.current = false;
    console.log('CAPTURE COMPLETED');
  };

  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      setStream(null);
      if (videoRef.current) {
        videoRef.current.srcObject = null;
      }
    }
  };

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id') || '';
    setSessionId(id);

    const initializeApp = async () => {
      await startCamera();
      
      if (id) {
        // Load existing photo count and setup initial timeout
        const currentCount = await loadPhotoCount(id);
        resetInactivityTimeout();
        
        // Check if already at max captures
        checkAndRedirectIfComplete(currentCount);
      }
    };

    initializeApp();

    if (id) {
      const channel = pusherClient.subscribe(`session-${id}`);
      
      channel.bind('capture-photo', () => {
        console.log('RECEIVED capture-photo event');
        resetInactivityTimeout(); // Reset timeout on activity
        startCountdown();
      });

      // Listen for photo-captured events to update counter
      channel.bind('photo-captured', async () => {
        console.log('RECEIVED photo-captured event');
        resetInactivityTimeout(); // Reset timeout on activity
        
        // Reload photo count to get accurate count
        const updatedCount = await loadPhotoCount(id);
        checkAndRedirectIfComplete(updatedCount);
      });

      return () => {
        pusherClient.unsubscribe(`session-${id}`);
        stopCamera();
        if (countdownRef.current) {
          clearInterval(countdownRef.current);
          countdownRef.current = null;
        }
        if (inactivityTimeoutRef.current) {
          clearTimeout(inactivityTimeoutRef.current);
          inactivityTimeoutRef.current = null;
        }
      };
    } else {
      return () => {
        stopCamera();
        if (countdownRef.current) {
          clearInterval(countdownRef.current);
          countdownRef.current = null;
        }
        if (inactivityTimeoutRef.current) {
          clearTimeout(inactivityTimeoutRef.current);
          inactivityTimeoutRef.current = null;
        }
      };
    }
  }, []);

  if (error) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-white text-center">
          <h1 className="text-2xl font-bold mb-4">❌ Camera Error</h1>
          <p className="mb-4">{error}</p>
          <button 
            onClick={startCamera}
            className="bg-blue-500 hover:bg-blue-600 px-6 py-3 rounded text-white font-semibold"
          >
            🔄 Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen w-screen bg-black relative overflow-hidden">
      <video
        ref={videoRef}
        autoPlay
        playsInline
        muted
        className="w-full h-full object-cover"
      />
      
      <canvas ref={canvasRef} className="hidden" />
      
      {/* Blinking overlay */}
      {isBlinking && (
        <div className="absolute inset-0 bg-white animate-pulse z-20"></div>
      )}
      
      {/* Countdown overlay */}
      {countdown !== null && (
        <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
          <div className="text-center">
            <div className="text-9xl font-bold mb-4 animate-bounce text-white drop-shadow-2xl" style={{textShadow: '4px 4px 8px rgba(0,0,0,0.8)'}}>
              {countdown}
            </div>
            <p className="text-2xl font-semibold text-white drop-shadow-lg" style={{textShadow: '2px 2px 4px rgba(0,0,0,0.8)'}}>Get Ready!</p>
          </div>
        </div>
      )}
      
      {/* Logo Live Camera */}
      <div className="absolute top-8 left-8 bg-red-500 bg-opacity-90 text-white px-4 py-2 rounded-lg flex items-center gap-2 z-5">
        <div className="w-3 h-3 bg-white rounded-full animate-pulse"></div>
        <span className="font-bold text-lg">LIVE</span>
      </div>

      {/* Photo Counter */}
      <div className="absolute top-8 right-8 bg-black bg-opacity-70 text-white px-4 py-2 rounded-lg z-5">
        <span className="font-bold text-lg">
          {photoCount}/{MAX_CAPTURES} Foto
        </span>
      </div>

      {/* Orientation Indicator */}
      <div className="absolute bottom-8 left-8 bg-gray-800 bg-opacity-80 text-white px-3 py-1 rounded-lg z-5">
        <span className="font-medium text-sm">
          📱 {CAMERA_ORIENTATION.charAt(0).toUpperCase() + CAMERA_ORIENTATION.slice(1)}
        </span>
      </div>

    </div>
  );
}