import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:qr_code_scanner/qr_code_scanner.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;
  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: DefaultButton(
                LocaleKeys.cancel.tr(),
                () {
                  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);
        }
      });
    });
  }

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