import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:generp/screens/notifierExports.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:provider/provider.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';

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

  @override
  State<InventoryScreen> createState() => _InventoryScreenState();
}

class _InventoryScreenState extends State<InventoryScreen> {
  FocusNode partIDfocusNode = FocusNode();
  TextEditingController partIDcontroller = 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 inventoryProvider = Provider.of<InventoryProvider>(
        context,
        listen: false,
      );
      inventoryProvider.checkPermission1();
      inventoryProvider.requestCameraPermission();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.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: () => onBackPressed(context),
              child: SafeArea(
                top: false,
                bottom: true,
                child: _scaffold(context),
              ),
            )
            : _scaffold(context)
        : NoNetwork(context);
  }

  Widget _scaffold(BuildContext context) {
    return Consumer<InventoryProvider>(
      builder: (context, provider, child) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.scaffold_bg_color,
          appBar: appbarNew(context, "Gen Inventory", 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, "inventory", 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(
                  "to open Inventory",
                  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 {
                    _showPartIdBottomSheet(context);
                  },
                  child: Text(
                    "Tap To Enter Part ID",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 17,
                      fontFamily: "JakartaMedium",
                      color: AppColors.app_blue,
                    ),
                  ),
                ),
                SizedBox(height: 50),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _showPartIdBottomSheet(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<InventoryProvider, HomescreenNotifier>(
                    builder: (context, provider, homeProvider, child) {
                      return SingleChildScrollView(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 10),
                              alignment: Alignment.topLeft,
                              child: Text(
                                "Part ID",
                                style: TextStyle(
                                  color: Color(0xFF818181),
                                  fontFamily: "JakartaMedium",
                                  fontSize: 14,
                                ),
                              ),
                            ),
                            SizedBox(height: 5),
                            Container(
                              height: 48,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(14),
                                border:
                                    partIDfocusNode.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: TextField(
                                  controller: partIDcontroller,
                                  keyboardType: TextInputType.text,
                                  focusNode: partIDfocusNode,
                                  textCapitalization:
                                      TextCapitalization.characters,

                                  style: TextStyle(fontSize: 14),
                                  onChanged: (value) {},
                                  onTapOutside: (event) {
                                    // Handle onTapOutside
                                    FocusScope.of(context).unfocus();
                                  },
                                  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 Part ID',
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap: () {
                                provider.LoadPartDetailsApifunction(
                                  homeProvider,
                                  context,
                                  "inventory",
                                  partIDcontroller.text,
                                );
                                partIDcontroller.clear();
                              },
                              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: Text(
                                    "Submit",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontFamily: "JakartaMedium",
                                      fontSize: 15,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
