'use client';

import { useEffect, useRef, useState } from 'react';
import { BrowserMultiFormatReader } from '@zxing/library';
import { scanQr } from '@/modules/sessionModule/qrScan/actions/cameraActions';
import { useNavigation } from '@/hooks/useNavigation';
import { isCameraStartActive, stopMediaStream } from '@/lib/cameraLifecycle';

type Props = {
  readonly isScanning: boolean;
  readonly onScanResult?: (result: string) => void;
  readonly onServerResponse?: (message: string) => void;
  readonly onError?: (error: string) => void;
};

export default function CameraPreview({ 
  isScanning, 
  onScanResult, 
  onServerResponse, 
  onError 
}: Props) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [cameraReady, setCameraReady] = useState(false);
  const [scanning, setScanning] = useState(false);
  const codeReaderRef = useRef<BrowserMultiFormatReader | null>(null);
  const cameraStartGenerationRef = useRef(0);
  const isMobile = useNavigation().isMobile;

  useEffect(() => {
    if (isScanning) {
      startCamera();
    } else {
      stopCamera();
    }

    return () => {
      stopCamera();
    };
  }, [isScanning]);

  const startCamera = async () => {
    const expectedGeneration = cameraStartGenerationRef.current;
    const isStartActive = () => isCameraStartActive({
      expectedGeneration,
      currentGeneration: cameraStartGenerationRef.current,
      isOpen: true,
    });

    try {
      if (!isStartActive()) return;
      const codeReader = new BrowserMultiFormatReader();
      codeReaderRef.current = codeReader;

      const videoInputDevices = await codeReader.listVideoInputDevices();
      if (!isStartActive()) return;
      const selectedDeviceId = videoInputDevices[0]?.deviceId;

      if (videoRef.current && selectedDeviceId) {
        await codeReader.decodeFromVideoDevice(
          selectedDeviceId,
          videoRef.current,
          async (result, error) => {
            if (result) {
              if (!isStartActive()) return;
              const text = result.getText();
              setScanning(true);
              
              onScanResult?.(text);

              const serverResponse = await scanQr(text);
              if (serverResponse.status === 'success') {
                onServerResponse?.(serverResponse.data);
              } else {
                onError?.(serverResponse.data);
              }
              
              setScanning(false);
            }
          }
        );
        if (!isStartActive()) {
          stopCamera();
          return;
        }
        setCameraReady(true);
      } else if (isStartActive()) {
        onError?.('No camera device detected.');
      }
    } catch (err: any) {
      if (!isStartActive()) return;
      console.error('Error starting camera:', err);
      if (err?.name === 'NotAllowedError') {
        onError?.('Camera access is blocked. Set this site\'s camera permission to Allow, then retry.');
      } else {
        onError?.('Failed to start camera. Please check permissions.');
      }
    }
  };

  const stopCamera = () => {
    cameraStartGenerationRef.current += 1;
    if (codeReaderRef.current) {
      codeReaderRef.current.reset();
      codeReaderRef.current = null;
    }
    if (videoRef.current?.srcObject) {
      stopMediaStream(videoRef.current.srcObject as MediaStream);
      videoRef.current.srcObject = null;
    }
    setCameraReady(false);
    setScanning(false);
  };

  if (!isScanning) {
    return (
      <div
        className={`relative bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900 rounded-2xl overflow-hidden shadow-xl flex items-center justify-center ${
          isMobile ? 'aspect-square' : 'aspect-video'
        }`}
      >
        <div className="text-center p-8">
          <div className="w-20 h-20 bg-gray-300 dark:bg-gray-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-10 h-10 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
          </div>
          <h3 className="text-xl font-semibold text-gray-700 dark:text-gray-300 mb-2">Camera Preview</h3>
          <p className="text-gray-500 dark:text-gray-400">Start camera to begin scanning</p>
        </div>
      </div>
    );
  }

  return (
    <div className="relative bg-black rounded-2xl overflow-hidden shadow-xl">
      <video
        ref={videoRef}
        className="w-full h-auto min-h-[400px] object-cover"
        playsInline
        muted
      />
      
      {/* Scanning overlay */}
      <div className="absolute inset-0 pointer-events-none">
        {/* Corner guides */}
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64">
          <div className="relative w-full h-full">
            {/* Top left corner */}
            <div className="absolute top-0 left-0 w-8 h-8 border-l-4 border-t-4 border-white opacity-80"></div>
            {/* Top right corner */}
            <div className="absolute top-0 right-0 w-8 h-8 border-r-4 border-t-4 border-white opacity-80"></div>
            {/* Bottom left corner */}
            <div className="absolute bottom-0 left-0 w-8 h-8 border-l-4 border-b-4 border-white opacity-80"></div>
            {/* Bottom right corner */}
            <div className="absolute bottom-0 right-0 w-8 h-8 border-r-4 border-b-4 border-white opacity-80"></div>
          </div>
        </div>

        {/* Scanning line animation */}
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64">
          <div className="animate-pulse">
            <div className="h-0.5 bg-gradient-to-r from-transparent via-brand-400 to-transparent animate-bounce"></div>
          </div>
        </div>
      </div>

      {/* Status indicators */}
      <div className="absolute top-4 left-4 right-4 flex justify-between items-start">
        <div className="bg-black/50 backdrop-blur-sm rounded-lg px-3 py-2">
          <div className="flex items-center space-x-2">
            <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
            <span className="text-white text-sm font-medium">
              {cameraReady ? 'Ready to scan' : 'Starting camera...'}
            </span>
          </div>
        </div>

        {scanning && (
          <div className="bg-blue-500/90 backdrop-blur-sm rounded-lg px-3 py-2">
            <div className="flex items-center space-x-2">
              <div className="w-2 h-2 bg-white rounded-full animate-ping"></div>
              <span className="text-white text-sm font-medium">Processing...</span>
            </div>
          </div>
        )}
      </div>

      {/* Bottom instruction */}
      <div className="absolute bottom-4 left-4 right-4">
        <div className="bg-black/50 backdrop-blur-sm rounded-lg px-4 py-3 text-center">
          <p className="text-white text-sm">Position QR code within the frame</p>
        </div>
      </div>
    </div>
  );
}
