/**
 * @file QrScanner
 * @description
 * This component handles real-time QR code scanning using the device camera.
 * It uses the `html5-qrcode` library to initialize the camera and process QR code data.
 * When a valid QR code is detected, the scanner stops automatically,
 * and callback functions are invoked to handle the scanned result and close the scanner.
 */

import React, { useEffect, useRef } from 'react';
import { Html5Qrcode } from 'html5-qrcode';

/**
 * QrScanner Component
 *
 * @component
 * @param {Function} onScanSuccess - Callback function to handle the scanned QR code value.
 * @param {Function} onClose - Callback function triggered when the scanner is stopped (can be used for cleanup or redirection).
 *
 * @returns  A div element where the camera stream and QR scanning UI will appear.
 */

const QrScanner = ({ onScanSuccess, onClose }) => {
  const scannerRef = useRef(null);
  const isStopped = useRef(false);

  useEffect(() => {
    const scanner = new Html5Qrcode('qr-scanner-region');
    scannerRef.current = scanner;

    scanner
      .start({ facingMode: 'environment' }, { fps: 10, qrbox: 250 }, async (decodedText) => {
        if (!isStopped.current) {
          isStopped.current = true;
          await scanner.stop(); // Ensure it's stopped only once
          onScanSuccess(decodedText);
          onClose(); // Let parent control redirection
        }
      })
      .catch((err) => {
        console.error('QR Scan Error:', err);
      });

    return () => {
      if (!isStopped.current) {
        isStopped.current = true;
        scanner.stop().catch((e) => {
          // console.warn("Stop error (likely already stopped):", e.message);
        });
      }
    };
  }, [onScanSuccess, onClose]);

  return <div id="qr-scanner-region" style={{ width: '100%', height: 300 }} />;
};

export default QrScanner;
