import React, { useState, useRef, useCallback } from 'react';
import Webcam from 'react-webcam';
import { QrReader } from 'react-qr-barcode-scanner';

const BarcodeScanner = () => {
  const [hasCameraPermission, setHasCameraPermission] = useState(false);
  const [barcodeData, setBarcodeData] = useState(null);
  const webcamRef = useRef(null);

  const handleUserMedia = useCallback(() => {
    setHasCameraPermission(true);
  }, []);

  const handleScan = (result) => {
    if (result) {
      setBarcodeData(result.text);
    }
  };

  const handleError = (error) => {
    console.error(error);
  };

  return (
    <div>
      <h1>Barcode Scanner</h1>
      {!hasCameraPermission ? (
        <Webcam
          audio={false}
          ref={webcamRef}
          screenshotFormat="image/jpeg"
          onUserMedia={handleUserMedia}
        />
      ) : (
        <QrReader
          onResult={handleScan}
          onError={handleError}
          style={{ width: '100%' }}
        />
      )}
      {barcodeData && (
        <div>
          <h2>Scanned Barcode:</h2>
          <p>{barcodeData}</p>
        </div>
      )}
    </div>
  );
};

export default BarcodeScanner;
