import 'package:flutter/material.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../widgets/widgets.dart';

class QRScanner extends StatefulWidget {
  final Function(QRInfo) onQRViewCreated;

  const QRScanner({Key? key, required this.onQRViewCreated}) : super(key: key);

  @override
  _QRScannerState createState() => _QRScannerState();
}

class _QRScannerState extends State<QRScanner> with WidgetsBindingObserver {
  late MobileScannerController controller;
  bool isHandlingQRcode = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    controller = MobileScannerController();
    controller.barcodes.listen(_handleBarcode);
    controller.start();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    controller.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        controller.start();
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
        controller.stop();
        break;
      case AppLifecycleState.detached:
        controller.dispose();
        break;
      default:
        break;
    }
  }

  void _handleBarcode(BarcodeCapture capture) async {
    if (isHandlingQRcode) return;

    final String? code = capture.barcodes.first.rawValue;
    if (code != null) {
      isHandlingQRcode = true;
      controller.stop();

      final qrData = QRValidacion.validarQR(code);

      if (qrData['isValid'] == 'true') {
        final qrInfo = QRInfo(
          idEmpresa: qrData['idEmpresa']!,
          numeroUnidad: qrData['numeroUnidad']!,
        );
        widget.onQRViewCreated(qrInfo);
      } else {
        await _showInvalidQRDialog();
        controller.start();
      }

      isHandlingQRcode = false;
    }
  }

  Future<void> _showInvalidQRDialog() async {
    return alerta(
      context,
      etiqueta: "El código QR escaneado no es válido.",
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: encabezado(titulo: "ESCANEA CÓDIGO QR"),
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 5,
            child: Stack(
              children: [
                MobileScanner(
                  controller: controller,
                  onDetect: _handleBarcode,
                ),
                QRScannerOverlay(),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class QRScannerOverlay extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final cutOutSize = 300.0;
        final borderLength = 30.0;
        final borderWidth = 10.0;
        final borderRadius = 10.0;
        final borderColor = Colors.red;

        return Stack(
          children: [
            Positioned(
              top: (constraints.maxHeight - cutOutSize) / 2,
              left: (constraints.maxWidth - cutOutSize) / 2,
              child: Container(
                width: cutOutSize,
                height: cutOutSize,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(borderRadius),
                  border: Border.all(
                    color: borderColor,
                    width: borderWidth,
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );
  }
}
