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

import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_repository.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/auth/login.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:toggle_switch/toggle_switch.dart';
import 'package:url_launcher/url_launcher.dart';

@RoutePage()
class NewQrPage extends StatefulWidget {
  const NewQrPage({Key? key}) : super(key: key);

  @override
  State<NewQrPage> createState() => _NewQrPageState();
}

class _NewQrPageState extends State<NewQrPage> {
  final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
  final ApiAuthRepository apiAuthRepository = ApiAuthRepository();
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  String? accCode = "";
  bool? _isAccCodeExist = false;

  String companyName = '';
  String serialNumber = '';
  String imageUrl = '';
  List lang = [];

  @override
  void initState() {
    try{imageUrl = apiAuthProvider.baseUrl + U.decodeBase64Url(Uri.decodeComponent(U.getAccessCode()!))+'/assets/background/tn';}catch(e){}
    getCompanyName();
    // TODO: implement initState
    super.initState();
  }

  getCompanyName() async {
    if (_sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyAccessCode)!) {
      var lics = await U.reloadLicense();
      if (lics != null && mounted) {
        setState(() {
          companyName = lics['companyName']??'';
          serialNumber = lics['serialNumber']??'';
          if(1698720817 <= lics['serverVersion']){
            lang = lics['languages'] != null ? lics['languages'].split(',') : [];
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // accCode = _sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessCode);
    // _isAccCodeExist = accCode != "" && accCode != null ? true : false;

    // var qp = context.router.current.queryParams;
    // bool _scanNew = false;
    //
    // if (qp.isNotEmpty) {
    //   _scanNew = qp.getString('new') == "true" ? true : false;
    // }
    // if (_isAccCodeExist! && !kIsWeb && !_scanNew){
    //   context.router.removeLast();
    //   context.navigateToPath("/app/${Uri.encodeComponent(accCode!)}/login");
    // }

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          SizedBox(
            width: double.infinity, height: double.infinity,
            child: Image.network(imageUrl, fit: BoxFit.cover, width: double.infinity, height: double.infinity, errorBuilder: (context, error, stackTrace) {
              return Image.asset('assets/image/background/background.jpg', fit: BoxFit.cover, width: double.infinity, height: double.infinity);
            }),
          ),
          SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.fromLTRB(16, kIsWeb?105:200, 16, 16),
              width: MediaQuery.of(context).size.width,
              height: kIsWeb && MediaQuery.of(context).size.height<700 ? 700 : MediaQuery.of(context).size.height,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter, end: Alignment.bottomCenter,
                      colors: [
                        primaryColor.withValues(alpha: 0.50), Colors.black.withValues(alpha: 0.91)
                      ]
                  )
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image.asset('assets/image/logo/logo.png', width: 160),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 100, left: 16, right: 16, bottom: 48),
                          child: kIsWeb?Column(
                            children: [
                              Text('noPIDText'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500), textAlign: TextAlign.center),
                              SizedBox(height: 16),
                              Text('noPIDText2'.tr(), style: TextStyle(color: Colors.white, fontSize: 16), textAlign: TextAlign.center),
                            ],
                          ):Text('scanQr'.tr(), style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w400), textAlign: TextAlign.center),
                        ),
                        !kIsWeb?GestureDetector(
                          onTap: scanDialog,
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 32, horizontal: 64),
                            decoration: BoxDecoration(
                                color: primaryColor.withValues(alpha: 0.50),
                                border: Border.all(color: Colors.white),
                                borderRadius: BorderRadius.all(Radius.circular(12))
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text('buttonScan'.tr(), style: TextStyle(color: Colors.white, fontSize: 16)),
                                SizedBox(width: 10),
                                U.iconsax('scan', color: Colors.white)
                              ],
                            ),
                          ),
                        ):Container(),
                        !kIsWeb && U.getAccessCode() != null ? Padding(
                            padding: EdgeInsets.only(top: 16),
                            child: GestureDetector(
                              child: Text('backToLogin'.tr(), style: TextStyle(color: Colors.white, fontSize: 14, decoration: TextDecoration.underline)),
                              onTap: (){
                                context.router.removeLast();
                                context.navigateToPath("/app/${U.getAccessCode()}/login");
                              },
                            )
                        ) : Container(),
                      ],
                    ),
                  ),

                  companyName.isNotEmpty?Text(companyName, style: TextStyle(fontSize: 16, color: Colors.white), textAlign: TextAlign.center):Container(),
                  SizedBox(height: 5),
                  serialNumber.isNotEmpty?Text('${'serialNumber'.tr()} $serialNumber', style: TextStyle(color: Colors.white, fontSize: 14)):Container(),
                  SizedBox(height: 5),
                  GestureDetector(
                    child: Text('policy'.tr(), style: TextStyle(color: Colors.white, fontSize: 14, decoration: TextDecoration.underline)),
                    onTap: () async {
                      Uri _url = Uri.parse('https://telmessenger.com/privacy-police/telnow.html');
                      await canLaunchUrl(_url) ? await launchUrl(_url) : print('Could not launch $_url');
                    },
                  ),
                  SizedBox(height: 5),
                  Text('${'version'.tr()} ${ApiAuthProvider().displayVersion}', style: TextStyle(color: Colors.white, fontSize: 14)),
                  SizedBox(height: 5),
                  Text('Build ${ApiAuthProvider().buildNumber}', style: TextStyle(color: Colors.white, fontSize: 13)),
                ],
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: kIsWeb?16:50, right: 16),
            child: Align(
              alignment: Alignment.topRight,
              child: lang.isNotEmpty ? GestureDetector(
                child: Container(
                  width: 65, height: 30, padding: EdgeInsets.symmetric(horizontal: 10),
                  decoration: BoxDecoration(
                      color: Colors.deepOrange,
                      borderRadius: BorderRadius.all(Radius.circular(50))
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      U.iconsax('bold/global', color: Colors.white),
                      Text(context.locale.toString().toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold))
                    ],
                  ),
                ),
                onTap: () => changeLangLogin(context, lang),
              ) : ToggleSwitch(
                minWidth: 40,
                minHeight: 30,
                cornerRadius: 20,
                initialLabelIndex: context.locale.toString() == 'en' ? 0 : 1,
                activeBgColor: [Colors.deepOrange],
                activeFgColor: Colors.white,
                inactiveBgColor: Colors.white54,
                inactiveFgColor: Colors.white,
                labels: ['EN', 'ID'],
                onToggle: (index) {
                  if (index == 0) {
                    context.setLocale(Locale('en'));
                  } else {
                    context.setLocale(Locale('id'));
                  }
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  Future scanDialog() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        // String barcode = await FlutterBarcodeScanner.scanBarcode('#ff6666', 'Cancel', true, ScanMode.QR);
        showModalBottomSheet<void>(
          context: context,
          backgroundColor: Colors.white,
          builder: (BuildContext contextt) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 15, bottom: 15),
                  child: Center(
                    child: Text('buttonScan'.tr(), style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
                  ),
                ),
                divider(),
                ListTile(
                  leading: Icon(Icons.image),
                  title: Text('fromGallery'.tr(), style: TextStyle(color: textColor)),
                  onTap: () async{
                    Navigator.of(contextt).pop();
                    XFile? file = await ImagePicker().pickImage(source: ImageSource.gallery);
                    if(file != null){
                      final BarcodeCapture? barcodeCapture = await MobileScannerController().analyzeImage(file.path);
                      String? str = barcodeCapture?.barcodes.singleOrNull?.displayValue;
                      if (str != null) {
                        scan(str);
                      }
                      else{
                        showError(context, 'messageInvalidCode'.tr());
                      }
                    }
                  },
                ),
                ListTile(
                  leading: Icon(Icons.camera),
                  title: Text('fromCamera'.tr(), style: TextStyle(color: textColor)),
                  onTap: () async{
                    Navigator.of(contextt).pop();
                    Navigator.push(context, MaterialPageRoute(builder: (context) => const ScanBarcodePage())).then((barcode){
                      if(barcode != null){
                        scan(barcode);
                      }
                    });
                  },
                )
              ],
            );
          }
        );
      }
    } on SocketException catch (_) {
      handlingError(context, 0); //no internet
    } on PlatformException catch (e) {
      if (e.code != '') {
        showError(context, 'messageCamPermission'.tr());
      } else {
        showError(context, 'messageInvalidCode'.tr());
      }
    } catch (e) {
      showError(context, 'messageInvalidCode'.tr());
    }
  }

  Future scan(String barcode) async {
// print("called scan()");
    try {
      var pidString = barcode.split("app/").last;
      var pid = Uri.decodeComponent(pidString.split('/').first);
      var splitPID = pid.split('#');
// print(splitPID);
// print(U.decodeBase64Url(splitPID[1]));

      await _sharedPreferencesManager.clearKey(SharedPreferencesManager.version);
      await _sharedPreferencesManager.putString(SharedPreferencesManager.keyBaseUrl, U.rewriteUrl(splitPID[1]));
      await _sharedPreferencesManager.putString(SharedPreferencesManager.keyAccessCode, splitPID[0]);
      await _sharedPreferencesManager.putString(SharedPreferencesManager.keySerialCode, 'P-${splitPID[0]}');
      apiAuthRepository.init();

      if (!pidString.contains('loginme')) {
        context.router.removeLast();
        context.navigateToPath("/app/${Uri.encodeComponent(splitPID[0])}/login");
      } else {
        context.router.removeLast();
        context.navigateToPath("/app/${Uri.encodeComponent(splitPID[0])}/loginme"+pidString.split("/loginme").last);
      }
    } catch (e) {
      print(e);
      showError(context, 'messageInvalidCode'.tr());
    }
  }
}


class ScanBarcodePage extends StatefulWidget {
  const ScanBarcodePage({super.key});

  @override
  State<ScanBarcodePage> createState() => _ScanBarcodePageState();
}

class _ScanBarcodePageState extends State<ScanBarcodePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MobileScanner(
        onDetect: (barcodes) {
          // print('sini');
          // print(barcodes.barcodes.singleOrNull?.displayValue);
          Navigator.of(context).pop(barcodes.barcodes.firstOrNull?.displayValue);
        },
      ),
    );
  }
}
