import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:generp/Notifiers/GeneratorDetailsProvider.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:provider/provider.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import '../../Notifiers/HomeScreenNotifier.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';

class Scanentergeneratoridscreen extends StatefulWidget {
  final from;

  const Scanentergeneratoridscreen({super.key, required this.from});

  @override
  State<Scanentergeneratoridscreen> createState() =>
      _ScanentergeneratoridscreenState();
}

class _ScanentergeneratoridscreenState
    extends State<Scanentergeneratoridscreen> {
  FocusNode genIDFocusNode = FocusNode();

  TextEditingController genIDcontroller = TextEditingController();

  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var provider = Provider.of<Generatordetailsprovider>(
        context,
        listen: false,
      );
      provider.initialFunction(widget.from);
      provider.checkPermission1();
      provider.requestCameraPermission();
      provider.checkLocationPermission1();
      provider.getLocationPermission(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    genIDcontroller.clear();
    genIDcontroller.dispose();
    _connectivity.disposeStream();
  }

  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    return (connection == "Online")
        ? Platform.isAndroid
            ? WillPopScope(
              onWillPop: () async {
                Provider.of<Generatordetailsprovider>(
                  context,
                  listen: false,
                ).resetForm();

                return onBackPressed(context);
              },
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<Generatordetailsprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () => onBackPressed(context),
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS ? false : true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.scaffold_bg_color,
              appBar: appbarNew(context, "${widget.from}", 0xFFFFFFFF),
              body: Container(
                decoration: BoxDecoration(color: Colors.black),
                child: Column(
                  children: [
                    Spacer(),
                    SizedBox(
                      height: 250,

                      child: QRView(
                        key: provider.scannerKey,
                        onQRViewCreated: (p0) {
                          provider.onQRViewCreated(p0, provider.title, context);
                        },
                        formatsAllowed: [BarcodeFormat.qrcode],
                        cameraFacing: CameraFacing.back,
                        overlay: QrScannerOverlayShape(
                          borderColor: AppColors.app_blue,
                          borderRadius: 20,
                          borderLength: 60,
                          borderWidth: 10,
                          cutOutSize: 250.0,
                        ),
                      ),
                    ),
                    SizedBox(height: 25),
                    Text(
                      "Scan QR",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 18,
                        fontFamily: "JakartaMedium",
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      provider.subTitle,
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 14, color: Colors.white),
                    ),

                    Spacer(),
                    Text(
                      "or",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 18,
                        fontFamily: "JakartaMedium",
                        color: Colors.white,
                      ),
                    ),
                    InkResponse(
                      onTap: () async {
                        provider.qrViewController!.pauseCamera();
                        provider.submitLoading = false;
                        _showgenIdBottomSheet(context);
                      },
                      child: Text(
                        "Tap to Enter Gen ID",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 18,
                          fontFamily: "JakartaMedium",
                          color: AppColors.app_blue,
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    // if(widget.from!="Tag Generator")
                    // Padding(
                    //   padding: EdgeInsets.symmetric(horizontal: 15),
                    //   child: Text(
                    //     provider.note,
                    //     textAlign: TextAlign.center,
                    //     style: TextStyle(
                    //       fontSize: 14,
                    //       color: AppColors.grey_semi,
                    //     ),
                    //   ),
                    // ),
                    SizedBox(height: 50),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Future<void> _showgenIdBottomSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      useRootNavigator: true,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Padding(
                padding: EdgeInsets.only(
                  bottom:
                      MediaQuery.of(
                        context,
                      ).viewInsets.bottom, // This handles keyboard
                ),
                child: Container(
                  margin: EdgeInsets.only(
                    bottom: 15,
                    left: 15,
                    right: 15,
                    top: 30,
                  ),

                  child: Consumer2<
                    Generatordetailsprovider,
                    HomescreenNotifier
                  >(
                    builder: (context, provider, homeProvider, child) {
                      return SingleChildScrollView(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 5,
                              ),
                              alignment: Alignment.topLeft,
                              child: Text(
                                "Gen ID",
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontFamily: "JakartaMedium",
                                  fontSize: 14,
                                ),
                              ),
                            ),
                            Container(
                              height: 48,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                                border:
                                    genIDFocusNode.hasFocus
                                        ? Border.all(
                                          color: AppColors.app_blue,
                                          width: 0.5,
                                        )
                                        : null,
                              ),
                              //  alignment: Alignment.center,
                              margin: EdgeInsets.only(left: 5.0, right: 5.0),
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(
                                  10.0,
                                  0.0,
                                  15,
                                  0,
                                ),
                                child: TextFormField(
                                  controller: genIDcontroller,
                                  keyboardType: TextInputType.text,

                                  textCapitalization:
                                      TextCapitalization.characters,
                                  focusNode: genIDFocusNode,
                                  style: TextStyle(fontSize: 14),
                                  onChanged: (value) {},
                                  onTapOutside: (event) {
                                    // Handle onTapOutside
                                    FocusScope.of(context).unfocus();
                                  },
                                  onFieldSubmitted: (value) {
                                    provider.submitLoading = true;
                                    provider.LoadgeneratorDetailsApifunction(
                                      homeProvider,
                                      context,
                                      widget.from,
                                      genIDcontroller.text,
                                      "1",
                                    );
                                    genIDcontroller.clear();
                                  },
                                  decoration: InputDecoration(
                                    isDense: true,
                                    hintStyle: TextStyle(
                                      color: Color(0xFF818181),
                                      fontSize: 14,
                                    ),
                                    //contentPadding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                    hintText: 'Enter Gen ID',
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap:
                                  provider.submitLoading
                                      ? null
                                      : () async {
                                        switch (widget.from) {
                                          case "Generator Details":
                                            provider.submitLoading = true;
                                            provider.LoadgeneratorDetailsApifunction(
                                              homeProvider,
                                              context,
                                              widget.from,
                                              genIDcontroller.text,
                                              "1",
                                            );
                                            genIDcontroller.clear();
                                            break;
                                          // case "Register Complaint":
                                          //   provider.LoadgeneratorDetailsApifunction(
                                          //     homeProvider,
                                          //     context,
                                          //     widget.from,
                                          //     genIDcontroller.text,
                                          //     "2"
                                          //   );
                                          //   break;
                                          // case "Tag Location":
                                          //   provider.TagLocationAPIFunction(homeProvider, context, genIDcontroller.text);
                                          //   break;
                                          case "Tag Generator":
                                            provider.submitLoading = false;
                                            provider.TagGeneratorCheckAPIFunction(
                                              homeProvider,
                                              context,
                                              genIDcontroller.text,
                                            );
                                            //  final data = await ApiCalling.TagGeneratorCheckAPI(homeProvider.empId, homeProvider.session, genIDcontroller.text);
                                            // if(data!=null){
                                            //   if(data.error==0){
                                            //     provider.showTagGeneratorBottomSheet(context, genIDcontroller.text);
                                            //   }else{
                                            //     toast(context, data.message);
                                            //   }
                                            // }

                                            break;
                                          default:
                                            break;
                                        }
                                      },
                              child: Container(
                                alignment: Alignment.center,
                                height: 45,
                                margin: EdgeInsets.only(
                                  left: 5.0,
                                  right: 5.0,
                                  top: 5.0,
                                  bottom: 5.0,
                                ),
                                decoration: BoxDecoration(
                                  color: AppColors.app_blue, //1487C9
                                  borderRadius: BorderRadius.circular(15.0),
                                ),
                                child: Center(
                                  child:
                                      provider.submitLoading
                                          ? CircularProgressIndicator.adaptive(
                                            valueColor: AlwaysStoppedAnimation(
                                              AppColors.white,
                                            ),
                                            padding: EdgeInsets.all(10),
                                          )
                                          : Text(
                                            "Search",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontFamily: "JakartaMedium",
                                              fontSize: 16,
                                            ),
                                          ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          },
        );
      },
    ).whenComplete(() {
      var provider = Provider.of<Generatordetailsprovider>(
        context,
        listen: false,
      );
      provider.qrViewController!.resumeCamera();
    });
  }
}
