
import 'package:flutter/material.dart';

import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_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;
  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: QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
              ),
            ),
            // 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: AppFilledButton(
                label: "LocaleKeys.cancel.tr()",
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;

    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        if (!isPicked) {
          isPicked = true;
          Navigator.pop(context, result!.code);
        }
      });
    });
    controller.pauseCamera();
    controller.resumeCamera();
  }

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