import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';

class QrScannerDialog extends StatefulWidget {
  @override
  State<QrScannerDialog> createState() => _QrScannerDialogState();
}

class _QrScannerDialogState extends State<QrScannerDialog> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  // Barcode? result;
  // QRViewController? controller;
  Barcode? _barcode;
  bool isPicked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.white,
        child: Column(
          children: [
            Expanded(
              flex: 1,
              child: MobileScanner(key : qrKey,onDetect: _handleBarcode),
            ),
            // Expanded(
            //   flex: 1,
            //   child: Center(
            //     child: (result != null)
            //         ? Text(
            //         'Barcode Type: ${result!.format}   Data: ${result!.code}')
            //         : Text('Scan a code'),
            //   ),
            // ),
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: DefaultButton(
                LocaleKeys.cancel.tr(),
                () {
                  Navigator.pop(context);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _handleBarcode(BarcodeCapture barcodes) {
    // this.controller = controller;
    Barcode? data = barcodes.barcodes.firstOrNull;
    if(data == null || isPicked) {
      return;
    }
    // controller.scannedDataStream.listen((scanData) {
      setState(() {
        // result = scanData;
          isPicked = true;
          Navigator.pop(context, data.displayValue);
      });
    // });
    // controller.pauseCamera();
    // controller.resumeCamera();
  }

  @override
  void dispose() {
    super.dispose();
  }
}
