import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:absenkuv3/Bloc/Patroli/AbsensiPatroliBloc.dart';
import 'package:absenkuv3/Bloc/Patroli/QrBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mPatroliPage.dart';
import 'package:absenkuv3/Repository/Model/mChekpoint.dart';
import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Patroli/HalamanTambahPatroli.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
// import 'package:qr_code_scanner/qr_code_scanner.dart' as qr_code_scanner;

class BarcodeScannerV1 extends StatefulWidget {
  final JadwalChekpoint? jadwalChekpoint;
  final MenuPatroli? redaksional;
  const BarcodeScannerV1({Key? key, this.jadwalChekpoint, this.redaksional})
      : super(key: key);
  @override
  _BarcodeScannerV1State createState() => _BarcodeScannerV1State();
}

class _BarcodeScannerV1State extends State<BarcodeScannerV1> {
  String overlayText = "Please scan QR Code";
  bool dataProcessed = false;
  bool camStarted = true;

  final MobileScannerController controller = MobileScannerController(
    formats: const [BarcodeFormat.qrCode],
    autoStart: true,
  );

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

  void onBarcodeDetect(BarcodeCapture barcodeCapture) {
    final barcode = barcodeCapture.barcodes.last;

    if (!dataProcessed) {
      setState(() {
        overlayText = barcodeCapture.barcodes.last.displayValue ??
            barcode.rawValue ??
            'Barcode has no displayable value';
      });

      processBarcodeData(overlayText);
    }
  }

  void processBarcodeData(String barcodeData) async {
    try {
      var userData = await sharedPreferences().getUserData();
      String bahasa = await sharedPreferences().getBahasa();
      if (barcodeData[0] == '{' && barcodeData[barcodeData.length - 1] == '}') {
        final Map<String, dynamic> jsonMap = json.decode(barcodeData);
        final String key = jsonMap['key'];
        String nm_lokasi = jsonMap["nm_lokasi"];
        print("ini id cabang" + userData.dataLogin!.idCabang.toString());
        print("ini id company" + userData.dataLogin!.idCompany.toString());
        print("qrflag" + userData.dataLogin!.qrcodeFlag.toString());
        dataProcessed = true;
        if (jsonMap.containsKey("key") && jsonMap.containsKey("nm_lokasi")) {
          if (key !=
              "${userData.dataLogin!.idCompany}${userData.dataLogin!.idCabang}") {
            showDialog(
              context: context,
              builder: (context) => AlertDialog(
                title: Text(bahasa == 'id'
                    ? "QR Code Tidak Terdaftar"
                    : "QR code not registered."),
                content: Text(bahasa == 'id'
                    ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
                    : "The QR code you scanned is not registered in the app. Please contact your admin."),
                actions: [
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                      dataProcessed = false;
                    },
                    child: Text("OK"),
                  ),
                ],
              ),
            );
          } else {
            Navigator.of(context).pushReplacement(MaterialPageRoute(
              builder: (context) => MultiBlocProvider(
                providers: [
                  BlocProvider<AbsensiPatroliBloc>(
                    create: (context) {
                      return AbsensiPatroliBloc(AbsensiPatroliLoading());
                    },
                  ),
                ],
                child: HalamanTambahPatroli(
                  jadwalChekpoint: widget.jadwalChekpoint,
                ),
              ),
              settings: RouteSettings(
                  arguments: nm_lokasi), // Pass 'gudang' as arguments
            ));
          }
        } else {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text(bahasa == 'id'
                  ? "QR Code Tidak Terdaftar"
                  : "QR code not registered."),
              content: Text(bahasa == 'id'
                  ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
                  : "The QR code you scanned is not registered in the app. Please contact your admin."),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    dataProcessed = false;
                  },
                  child: Text("OK"),
                ),
              ],
            ),
          );
        }
      } else {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(bahasa == 'id'
                ? "QR Code Tidak Terdaftar"
                : "QR code not registered."),
            content: Text(bahasa == 'id'
                ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
                : "The QR code you scanned is not registered in the app. Please contact your admin."),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  dataProcessed = false;
                },
                child: Text("OK"),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      print('Gagal melakukan deserialisasi JSON atau mengambil nilai "key".');
    }
  }

  @override
  Widget build(BuildContext context) {
    final scanWindow = Rect.fromCenter(
      center: MediaQuery.of(context).size.center(Offset.zero),
      width: 250,
      height: 250,
    );

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        flexibleSpace: Image(
          image: AssetImage(ValueImage.headerBiruDashboard),
          fit: BoxFit.cover,
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: Text(
          'Scan Qr',
          style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
        ),
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: Stack(
                fit: StackFit.expand,
                children: [
                  Center(
                    child: MobileScanner(
                      fit: BoxFit.cover,
                      onDetect: onBarcodeDetect,
                      controller: controller,
                      scanWindow: scanWindow,
                    ),
                  ),
                  Positioned(
                    top: 16.0,
                    right: 16.0,
                    child: Container(
                      padding: EdgeInsets.all(3),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(100),
                          color: Colors.white),
                      child: IconButton(
                          onPressed: () async {
                            await controller?.toggleTorch();
                            // setState(() {});
                          },
                          icon: Icon(
                            Icons.flash_on,
                            color: Colors.black,
                          )),
                    ),
                  ),
                  // Positioned(
                  //   top: -50,
                  //   left: 0,
                  //   right: 0,
                  //   child: ScannerOverlay(scanWindow),
                  // ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: ScanCard(),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ScannerOverlay extends StatelessWidget {
  final Rect scanWindow;

  ScannerOverlay(this.scanWindow);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: _ScannerOverlayPainter(scanWindow),
    );
  }
}

class _ScannerOverlayPainter extends CustomPainter {
  final Rect scanWindow;
  final double borderRadius = 12.0;

  _ScannerOverlayPainter(this.scanWindow);

  @override
  void paint(Canvas canvas, Size size) {
    final backgroundPath = Path()..addRect(Rect.largest);
    final cutoutPath = Path()
      ..addRRect(
        RRect.fromRectAndCorners(
          scanWindow,
          topLeft: Radius.circular(borderRadius),
          topRight: Radius.circular(borderRadius),
          bottomLeft: Radius.circular(borderRadius),
          bottomRight: Radius.circular(borderRadius),
        ),
      );

    final backgroundPaint = Paint()
      ..color = Colors.black.withOpacity(0.5)
      ..style = PaintingStyle.fill
      ..blendMode = BlendMode.dstOut;

    final backgroundWithCutout = Path.combine(
      PathOperation.difference,
      backgroundPath,
      cutoutPath,
    );

    // Create a Paint object for the white border
    final borderPaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.stroke
      ..strokeWidth = 4.0; // Adjust the border width as needed

    final borderRect = RRect.fromRectAndCorners(
      scanWindow,
      topLeft: Radius.circular(borderRadius),
      topRight: Radius.circular(borderRadius),
      bottomLeft: Radius.circular(borderRadius),
      bottomRight: Radius.circular(borderRadius),
    );

    // Draw the white border
    canvas.drawPath(backgroundWithCutout, backgroundPaint);
    canvas.drawRRect(borderRect, borderPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

class ScanCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: PengaturanBahasa().getDataBahasa(),
      builder: (BuildContext context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Card(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Container(
                  margin:
                      EdgeInsets.only(top: 20, left: 50, right: 50, bottom: 20),
                  child: Column(children: [
                    Text(
                      snapshot.data =='id'? "Arahkan kamera ke kode Qr untuk \n melakukan chekpoint":"Point your camera at the QR code \n to chekpoint.",
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      softWrap: false,
                      style: TextStyle(fontSize: 20, color: Colors.grey[600]),
                    )
                  ]),
                ),
              ],
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}

// class QRViewExample extends StatefulWidget {
//   // final String? dataAbsen;
//   final JadwalChekpoint? jadwalChekpoint;
//   final MenuPatroli? redaksional;
//   const QRViewExample({Key? key, this.jadwalChekpoint, this.redaksional})
//       : super(key: key);
//   @override
//   State<StatefulWidget> createState() => _QRViewExampleState();
// }
//
// class _QRViewExampleState extends State<QRViewExample> {
//   qr_code_scanner.Barcode? result;
//   qr_code_scanner.QRViewController? controller;
//   final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
//   @override
//   void reassemble() {
//     super.reassemble();
//     if (Platform.isAndroid) {
//       controller!.pauseCamera();
//     }
//     controller!.resumeCamera();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       backgroundColor: Colors.white,
//       appBar: AppBar(
//         flexibleSpace: Image(
//           image: AssetImage(ValueImage.headerBiruDashboard),
//           fit: BoxFit.cover,
//         ),
//         backgroundColor: Colors.transparent,
//         centerTitle: true,
//         title: Text(
//           'Scan Qr',
//           style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
//         ),
//       ),
//       body: BlocBuilder<QRBloc, QRState>(
//         builder: (context, state) {
//           if (state.status == QRStatus.scanning) {
//             return _buildScanningView();
//           } else if (state.status == QRStatus.scanned) {
//             return _buildScannedView(state.qrData!);
//           } else if (state.status == QRStatus.error) {
//             return _buildErrorView();
//           } else {
//             return _buildInitialView();
//           }
//         },
//       ),
//     );
//   }
//
//   Widget _buildInitialView() {
//     return FutureBuilder<PagePatroliModel>(
//         future: PengaturanBahasa().patroli(),
//         builder: (BuildContext context, snapshot) {
//           // if (snapshot.connectionState == ConnectionState.done) {
//           return Column(
//             children: <Widget>[
//               Expanded(
//                   flex: 4,
//                   child: Stack(
//                     children: <Widget>[
//                       _buildQrView(context),
//                       Positioned(
//                         top: 16.0,
//                         right: 16.0,
//                         child: Container(
//                           padding: EdgeInsets.all(3),
//                           decoration: BoxDecoration(
//                               borderRadius: BorderRadius.circular(100),
//                               color: Colors.white),
//                           child: IconButton(
//                               onPressed: () async {
//                                 await controller?.toggleFlash();
//                                 setState(() {});
//                               },
//                               icon: Icon(
//                                 Icons.flash_on,
//                                 color: Colors.black,
//                               )),
//                         ),
//                       )
//                     ],
//                   )),
//               Expanded(
//                 flex: 1,
//                 child: FittedBox(
//                   fit: BoxFit.contain,
//                   child: Column(
//                     mainAxisAlignment: MainAxisAlignment.spaceEvenly,
//                     children: <Widget>[
//                       Container(
//                         margin: EdgeInsets.only(
//                             top: 20, left: 50, right: 50, bottom: 20),
//                         child: Column(children: [
//                           Text(
//                             // "${widget.redaksional!.qr!.description}",
//                             // "${redaksinoal!.qr!.description}",
//                             // ,
//                             "${snapshot.data!.menuPatroli!.qr!.description}",
//                             // "Arahkan kamera ke kode Qr untuk \n melakukan chekpoint",
//                             textAlign: TextAlign.center,
//                             maxLines: 2,
//                             softWrap: false,
//                             style: TextStyle(
//                                 fontSize: 20, color: Colors.grey[600]),
//                           )
//                         ]),
//                       ),
//                     ],
//                   ),
//                 ),
//               )
//
//             ],
//           );
//         });
//   }
//
//   Widget _buildScanningView() {
//     return Center(
//       child: CircularProgressIndicator(),
//     );
//   }
//
//   Widget _buildScannedView(String qrData) {
//     return Center(
//       child: Column(
//         mainAxisAlignment: MainAxisAlignment.center,
//         children: <Widget>[
//           Text('Scanned QR Code: $qrData'),
//           ElevatedButton(
//             onPressed: () {
//               // widget.qrBloc.reset();
//             },
//             child: Text('Scan Again'),
//           ),
//         ],
//       ),
//     );
//   }
//
//   Widget _buildErrorView() {
//     return Center(
//       child: Column(
//         mainAxisAlignment: MainAxisAlignment.center,
//         children: <Widget>[
//           Text('Error scanning QR Code. Please try again.'),
//           ElevatedButton(
//             onPressed: () {
//               // widget.qrBloc.reset();
//             },
//             child: Text('Try Again'),
//           ),
//         ],
//       ),
//     );
//   }
//
//   Widget _buildQrView(BuildContext context) {
//     var scanArea = (MediaQuery.of(context).size.width < 400 ||
//             MediaQuery.of(context).size.height < 400)
//         ? 150.0
//         : 300.0;
//     return qr_code_scanner.QRView(
//       key: qrKey,
//       onQRViewCreated: _onQRViewCreated,
//       // overlay: qr_code_scanner.QrScannerOverlayShape(
//       //     borderColor: Colors.white,
//       //     borderRadius: 10,
//       //     borderLength: 30,
//       //     borderWidth: 10,
//       //     cutOutSize: scanArea),
//       onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
//     );
//   }
//
//   StreamSubscription? scanSubscription;
//   void _onQRViewCreated(qr_code_scanner.QRViewController controller) {
//     setState(() {
//       this.controller = controller;
//     });
//     scanSubscription = controller.scannedDataStream.listen((scanData) {
//       setState(() async {
//         result = scanData;
//         String qrCodeData = scanData.code.toString();
//         print("yayang awal string" + qrCodeData[0]);
//         print("yayang akhir" + qrCodeData[qrCodeData.length - 1]);
//         String bahasa = await sharedPreferences().getBahasa();
//         if (qrCodeData[0] == '{' && qrCodeData[qrCodeData.length - 1] == '}') {
//           Map<String, dynamic> decodedData = json.decode(qrCodeData);
//           if (decodedData.containsKey("key") &&
//               decodedData.containsKey("nm_lokasi")) {
//             var userData = await sharedPreferences().getUserData();
//             print("ini id cabang" + userData.dataLogin!.idCabang.toString());
//             print("ini id company" + userData.dataLogin!.idCompany.toString());
//             print("kamera" + userData.dataLogin!.kamera.toString());
//             String gudang = decodedData["nm_lokasi"];
//             String key = decodedData["key"];
//             if (key !=
//                 "${userData.dataLogin!.idCompany}${userData.dataLogin!.idCabang}") {
//               showDialog(
//                   context: context,
//                   builder: (context) => AlertDialog(
//                         title: Text(bahasa == 'id'
//                             ? "QR Code Tidak Terdaftar"
//                             : "QR code not registered."),
//                         content: Text(bahasa == 'id'
//                             ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
//                             : "The QR code you scanned is not registered in the app. Please contact your admin."),
//                         actions: [
//                           TextButton(
//                             onPressed: () {
//                               Navigator.of(context).pop();
//                               Navigator.of(context).pushReplacement(
//                                 MaterialPageRoute(
//                                   builder: (context) => QRViewExample(),
//                                 ),
//                               );
//                             },
//                             child: Text("OK"),
//                           ),
//                         ],
//                       ));
//             } else {
//               setState(() {
//                 result = scanData;
//               });
//               Navigator.of(context).pushReplacement(MaterialPageRoute(
//                 builder: (context) => MultiBlocProvider(
//                   providers: [
//                     BlocProvider<AbsensiPatroliBloc>(
//                       create: (context) {
//                         return AbsensiPatroliBloc(AbsensiPatroliLoading());
//                       },
//                     ),
//                   ],
//                   child: HalamanTambahPatroli(
//                     jadwalChekpoint: widget.jadwalChekpoint,
//                   ),
//                 ),
//                 settings: RouteSettings(
//                     arguments: gudang), // Pass 'gudang' as arguments
//               ));
//             }
//             if (scanSubscription != null) {
//               scanSubscription!.cancel();
//             }
//           } else {
//             showDialog(
//               context: context,
//               barrierDismissible: false,
//               builder: (context) => AlertDialog(
//                 title: Text(bahasa == 'id'
//                     ? "QR Code Tidak Terdaftar"
//                     : "QR code not registered."),
//                 content: Text(bahasa == 'id'
//                     ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
//                     : "The QR code you scanned is not registered in the app. Please contact your admin."),
//                 actions: [
//                   TextButton(
//                     onPressed: () {
//                       Navigator.of(context).pop();
//                       Navigator.of(context).pushReplacement(
//                         MaterialPageRoute(
//                           builder: (context) => QRViewExample(),
//                         ),
//                       );
//                     },
//                     child: Text("OK"),
//                   ),
//                 ],
//               ),
//             );
//             if (scanSubscription != null) {
//               scanSubscription!.cancel();
//             }
//           }
//         } else {
//           showDialog(
//             context: context,
//             barrierDismissible: false,
//             builder: (ctx) => AlertDialog(
//               title: Text(bahasa == 'id'
//                   ? "QR Code Tidak Terdaftar"
//                   : "QR code not registered."),
//               content: Text(bahasa == 'id'
//                   ? "QR Code Yang Dipindai Tidak Terdaftar Pada Aplikasi, Silahkan Hubungi Admin Anda."
//                   : "The QR code you scanned is not registered in the app. Please contact your admin."),
//               actions: [
//                 TextButton(
//                   onPressed: () {
//                     Navigator.of(context).pop();
//                     Navigator.of(ctx).pushReplacement(
//                       MaterialPageRoute(
//                         builder: (ctx) => QRViewExample(),
//                       ),
//                     );
//                   },
//                   child: Text("OK"),
//                 ),
//               ],
//             ),
//           );
//           if (scanSubscription != null) {
//             scanSubscription!.cancel();
//           }
//         }
//       });
//     });
//   }
//
//   void _onPermissionSet(
//       BuildContext context, qr_code_scanner.QRViewController ctrl, bool p) {
//     if (!p) {
//       ScaffoldMessenger.of(context).showSnackBar(
//         const SnackBar(content: Text('No Permission')),
//       );
//     }
//   }
// }
