import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/screens/screensExports.dart';
import 'package:generp/services/api_calling.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geolocator/geolocator.dart' as geo_location;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:location/location.dart' as Location;
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import '../Models/generatorComplaintResponse.dart';
import '../Models/loadGeneratorDetailsResponse.dart';
import '../Utils/app_colors.dart';
import 'HomeScreenNotifier.dart';

class Generatordetailsprovider extends ChangeNotifier {
  bool _submitLoading = false;
  bool _showMoreScheduleDetails = false;
  bool _showMoreScheduleList = false;
  PermissionStatus _cameraPermissionStatus = PermissionStatus.denied;
  PermissionStatus _LocationPermissionStatus = PermissionStatus.denied;
  final GlobalKey scannerKey = GlobalKey(debugLabel: 'QR');
  bool _hasPermission = false;
  bool _hasLocationPermission = false;
  bool isLocationEnabled = false;
  QRViewController? _qrViewController;
  TextEditingController engNoController = TextEditingController();
  FocusNode engineNoFocusNode = FocusNode();
  List<C_List> _complaintList = [];
  String? _genID = "-";
  String? _genHashID = "-";
  String? _aname = "-";
  String? _emodel = "-";
  String? _spname = "-";
  String? _mob1 = "-";
  String? _mob2 = "-";
  String? _mail = "-";
  String? _cname = "-";
  String? _engineNo = "-";
  String? _dateOfEngineSale = "-";
  String? _altNo = "-";
  String? _btryNo = "-";
  String? _dgSetNo = "-";
  String? _state = "-";
  String? _district = "-";
  String? _address = "-";
  String? _dispDate = "-";
  String? _cmsngDate = "-";
  String? _status = "-";
  String? _genLocation = "-";
  String? _genLocationLatLngs;
  String _title = "-";
  String _subTitle = "-";
  bool _isLoading = false;
  String? _scannedGenID;
  final ImagePicker _picker = ImagePicker();

  File? _image;
  File? _imageName;
  int _imagePicked = 0;
  LatLng startLocation = const LatLng(17.439112226708446, 78.43292499146135);
  LatLng? currentLocationLatLng;
  String latlongs = "";
  List<ComplaintTypeList> _complaintTypeDropdown = [];
  List<ComplaintCategoryList> _complaintCategorydropdown = [];
  List<ComplaintDescriptionList> _complaintDescriptionDropdown = [];
  List<ContactList> _contactList = [];
  List<ScheduleList> _scheduleList = [];

  ComplaintTypeList? _selectedComplaintType;
  ComplaintCategoryList? _selectedCategoryType;
  ComplaintDescriptionList? _selectedDescriptionType;

  List<ContactList> get contactsList => _contactList;

  List<ScheduleList> get scheduleList => _scheduleList;

  File? get image => _image;

  File? get imagePath => _imageName;

  int get imagePicked => _imagePicked;

  String? _imageError;

  String? get imageError => _imageError;

  set imagePath(File? value) {
    _imageName = value;
    notifyListeners();
  }

  set imageFilePath(File? value) {
    _image = value;
    notifyListeners();
  }

  set imagePicked(value) {
    _imagePicked = value;
    notifyListeners();
  }

  String? _selectedType;
  String? _selectedTypeId;

  String? _selectedCategory;
  String? _selectedCategoryId;

  String? _selectedDescription;
  String? _selectedDescriptionId;

  bool get submitLoading => _submitLoading;

  bool get showMoreScheduleDetails => _showMoreScheduleDetails;

  bool get showMoreScheduleList => _showMoreScheduleList;

  List<ComplaintTypeList> get complaintTypeDropdown => _complaintTypeDropdown;

  List<ComplaintCategoryList> get complaintCategorydropdown =>
      _complaintCategorydropdown;

  List<ComplaintDescriptionList> get complaintDescriptionDropdown =>
      _complaintDescriptionDropdown;

  ComplaintTypeList? get selectedComplaintType => _selectedComplaintType;

  ComplaintCategoryList? get selectedCategoryType => _selectedCategoryType;

  ComplaintDescriptionList? get selectedDescriptionType =>
      _selectedDescriptionType;

  String get title => _title;

  String get subTitle => _subTitle;

  String? get selectedType => _selectedType;

  String? get selectedCategory => _selectedCategory;

  String? get selectedDescription => _selectedDescription;

  String? get selectedTypeId => _selectedTypeId;

  String? get selectedCategoryId => _selectedCategoryId;

  String? get selectedDescriptionId => _selectedDescriptionId;

  List<C_List> get complaintList => _complaintList;

  String? get genID => _genID;

  String? get genHashID => _genHashID;

  String? get aname => _aname;

  String? get emodel => _emodel;

  String? get spname => _spname;

  String? get mob1 => _mob1;

  String? get mob2 => _mob2;

  String? get mail => _mail;

  String? get cname => _cname;

  String? get engineNo => _engineNo;

  String? get dateOfEngineSale => _dateOfEngineSale;

  String? get altNo => _altNo;

  String? get btryNo => _btryNo;

  String? get dgSetNo => _dgSetNo;

  String? get state => _state;

  String? get district => _district;

  String? get address => _address;

  String? get dispDate => _dispDate;

  String? get cmsngDate => _cmsngDate;

  String? get status => _status;

  String? get genLocation => _genLocation;

  String? get genLocationLatLngs => _genLocationLatLngs;

  bool get isLoading => _isLoading;

  bool get hasPermission => _hasPermission;

  bool get hasLocationPermission => _hasLocationPermission;

  String? get scannedGenID => _scannedGenID;

  QRViewController? get qrViewController => _qrViewController;

  set genLocationLatLngs(String? value) {
    _genLocationLatLngs = value;
    notifyListeners();
  }

  set submitLoading(bool value) {
    _submitLoading = value;
    notifyListeners();
  }

  set showMoreScheduleList(bool value) {
    _showMoreScheduleList = value;
    notifyListeners();
  }

  set showMoreScheduleDetails(bool value) {
    _showMoreScheduleDetails = value;
    notifyListeners();
  }

  set scannedGenID(String? id) {
    _scannedGenID = id;
    notifyListeners();
  }

  set selectedComplaintType(value) {
    _selectedComplaintType = value;
    _selectedType = value.name;
    _selectedTypeId = value.id;
    notifyListeners();
  }

  set selectedCategoryType(value) {
    _selectedCategoryType = value;
    _selectedCategory = value.name;
    _selectedCategoryId = value.id;
    notifyListeners();
  }

  set selectedDescriptionType(value) {
    _selectedDescriptionType = value;
    _selectedDescription = value.name;
    _selectedDescriptionId = value.id;
    notifyListeners();
  }

  set selectedType(value) {
    _selectedType = value;
    notifyListeners();
  }

  set selectedTypeId(value) {
    _selectedTypeId = value;
    notifyListeners();
  }

  set selectedCategory(value) {
    _selectedCategory = value;
    notifyListeners();
  }

  set selectedCategoryId(value) {
    _selectedCategoryId = value;
    notifyListeners();
  }

  set selectedDescription(value) {
    _selectedDescription = value;
  }

  set selectedDescriptionId(value) {
    _selectedDescriptionId = value;
  }

  void resetForm() {
    engNoController.clear();
    _selectedComplaintType = null;
    _selectedCategoryType = null;
    _selectedDescriptionType = null;
    _selectedType = "";
    _selectedTypeId = "";
    _selectedCategory = "";
    _selectedCategoryId = "";
    _selectedDescriptionId = "";
    _selectedDescription = "";
    _qrViewController!.dispose();
    _imageName = null;
    _image = null;
    _imagePicked = 0;
    _imageError = null;
    notifyListeners();
  }

  initialFunction(from) async {
    switch (from) {
      case "Generator Details":
        _title = "Generator Details";
        _subTitle = "to open Generator Details";
        notifyListeners();
        break;
      case "Register Complaint":
        _title = "Register Complaint";
        _subTitle = "to open Register Complaint";
        notifyListeners();
        break;
      case "Tag Location":
        _title = "Tag Location";
        _subTitle = "To Tag Location";
        notifyListeners();
        break;
      case "Tag Generator":
        _title = "Tag Generator";
        _subTitle = "To Tag Generator";
        notifyListeners();
        break;
      default:
        break;
    }
    notifyListeners();
  }

  Future<void> checkPermission1() async {
    // Check camera permissions
    var status = await Permission.camera.status;
    try {
      if (status.isGranted) {
        _hasPermission = true;
      } else if (status.isDenied || status.isRestricted) {
        // Request camera permissions if denied or restricted
        await Permission.camera.request();
        status = await Permission.camera.request();
        if (status.isGranted) {
          _hasPermission = true;
        } else {
          _hasPermission = false;
        }
      }
    } catch (e, s) {}
  }

  Future<void> checkLocationPermission1() async {
    // Check camera permissions
    var status = await Permission.location.status;
    try {
      if (status.isGranted) {
        _hasLocationPermission = true;
      } else if (status.isDenied || status.isRestricted) {
        // Request camera permissions if denied or restricted
        await Permission.location.request();
        status = await Permission.location.request();
        if (status.isGranted) {
          _hasLocationPermission = true;
        } else {
          _hasLocationPermission = false;
        }
      }
    } catch (e, s) {}
  }

  Future<void> requestCameraPermission() async {
    PermissionStatus status = await Permission.camera.request();

    _cameraPermissionStatus = status;
    // print(_cameraPermissionStatus);

    try {
      if (_cameraPermissionStatus.isGranted) {
        _hasPermission = true;
      } else if (_cameraPermissionStatus.isDenied ||
          _cameraPermissionStatus.isRestricted ||
          _cameraPermissionStatus.isPermanentlyDenied) {
        _hasPermission = false;
        await Permission.camera.request();
      }
    } catch (e, s) {}
  }

  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.camera.request();

    _LocationPermissionStatus = status;
    // print(_cameraPermissionStatus);

    try {
      if (_LocationPermissionStatus.isGranted) {
        _hasLocationPermission = true;
      } else if (_LocationPermissionStatus.isDenied ||
          _LocationPermissionStatus.isRestricted ||
          _LocationPermissionStatus.isPermanentlyDenied) {
        _hasLocationPermission = false;
        await Permission.location.request();
      }
    } catch (e, s) {}
  }

  Future<void> getLocationPermission(BuildContext context) async {
    isLocationEnabled = await Geolocator.isLocationServiceEnabled();
    LocationPermission permission = await Geolocator.checkPermission();
    _hasLocationPermission =
        permission == LocationPermission.always ||
        permission == LocationPermission.whileInUse;

    final Location.Location location = Location.Location();

    if (!isLocationEnabled || !hasLocationPermission) {
      permission = await Geolocator.requestPermission();
      if (permission != LocationPermission.always &&
          permission != LocationPermission.whileInUse) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Location Permission Required'),
              content: Text(
                'Please allow the app to access your location for core functionality.',
              ),
              actions: <Widget>[
                TextButton(
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.white),
                    overlayColor: MaterialStateProperty.all(Colors.white),
                  ),
                  onPressed: () async {
                    // await openAppSettings();
                    // Navigator.of(context).pop();
                    // Navigator.pushReplacement(
                    //   context,
                    //   MaterialPageRoute(builder: (context) => Attendance()),
                    // );
                  },
                  child: Text('OK'),
                ),
              ],
            );
          },
        );
        return;
      }
    }

    final Location.LocationData locData = await location.getLocation();
    if (locData != null) {
      currentLocationLatLng = LatLng(locData.latitude!, locData.longitude!);

      latlongs = '${locData.latitude},${locData.longitude}';

      notifyListeners();
    }
  }

  Future<void> getCurrentLocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: geo_location.LocationAccuracy.high,
      );
      currentLocationLatLng = LatLng(position.latitude, position.longitude);
      notifyListeners();
    } catch (e) {
      print("Error getting current location: $e");
    }
  }

  void onQRViewCreated(QRViewController controller, from, context) {
    // print("QRVIEW");
    var HomeProvider = Provider.of<HomescreenNotifier>(context, listen: false);
    this._qrViewController = controller;
    controller.scannedDataStream.listen((scanData) {
      controller!.pauseCamera();
      if (from == "Generator Details") {
        _genID = scanData.code;
        _genHashID = scanData.code;
        notifyListeners();
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Generatordetails(generatorId: scanData.code),
          ),
        );
      } else if (from == "Register Complaint") {
        _genID = scanData.code;
        _genHashID = scanData.code;
        notifyListeners();
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Registercomplaint()),
        );
      } else if (from == "Tag Location") {
        _genID = scanData.code;
        _genHashID = scanData.code;
        notifyListeners();
        print(scanData.code);
        TagLocationAPIFunction(HomeProvider, context, scanData.code, "Scanner");
      } else if (from == "Tag Generator") {
        _genID = scanData.code;
        _genHashID = scanData.code;
        notifyListeners();
        print(scanData.code);
        showTagGeneratorBottomSheet(context, scanData.code);
        // TagGeneraorAPIFunction(HomeProvider, context, scanData.code);
      }
    });
  }

  Future<void> LoadgeneratorDetailsApifunction(
    homeProvider,
    BuildContext context,
    from,
    genID, [
    number,
  ]) async {
    print("$number index calling");
    try {
      _submitLoading = true;
      notifyListeners();
      final data = await ApiCalling.LoadGeneratorDetailsAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
      );

      if (data != null) {
        if (data.error == 0) {
          _submitLoading = false;
          _genID = data.genId;
          _genHashID = data.genHashId;
          _aname = data.aname;
          _emodel = data.emodel;
          _spname = data.spname;
          _mob1 = data.mob1;
          _mob2 = data.mob2;
          _mail = data.mail;
          _cname = data.cname;
          _engineNo = data.engineNo;
          _dateOfEngineSale = data.dateOfEngineSale;
          _altNo = data.altNo;
          _btryNo = data.btryNo;
          _dgSetNo = data.dgSetNo;
          _state = data.state;
          _district = data.district;
          _address = data.address;
          _dispDate = data.dispDate;
          _cmsngDate = data.cmsngDate;
          _status = data.status;
          _genLocation = data.loc;
          _contactList = data.contactList ?? [];
          _scheduleList = data.scheduleList ?? [];
          _complaintTypeDropdown = data.complaintTypeList ?? [];
          _complaintCategorydropdown = data.complaintCategoryList ?? [];
          _complaintDescriptionDropdown = data.complaintDescriptionList ?? [];
          if (_selectedComplaintType != null &&
              !_complaintTypeDropdown.contains(_selectedComplaintType)) {
            _selectedComplaintType = null;
            _selectedType = "";
            _selectedTypeId = "";
          }

          if (_selectedCategoryType != null &&
              !_complaintCategorydropdown.contains(_selectedCategoryType)) {
            _selectedCategoryType = null;
            _selectedCategory = "";
            _selectedCategoryId = "";
          }

          if (_selectedDescriptionType != null &&
              !_complaintDescriptionDropdown.contains(
                _selectedDescriptionType,
              )) {
            _selectedDescriptionType = null;
            _selectedDescription = "";
            _selectedDescriptionId = "";
          }
          notifyListeners();
          Navigator.pop(context);
          if (from == "Generator Details") {
            this._qrViewController!.pauseCamera();
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder:
                    (context) => Generatordetails(
                      generatorId: _genID,
                      activityName: "Generator Details",
                    ),
              ),
              (Route<dynamic> route) {
                return route.settings.arguments == 'Gentrackerdashboard';
              },
            );
          } else if (from == "Register Complaint") {
            this._qrViewController!.pauseCamera();
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => Registercomplaint()),
            );
          }
        } else if (data.error == 1) {
          toast(context, "Enter Correct ID");
          _submitLoading = false;
          notifyListeners();
        } else {
          _submitLoading = false;
          notifyListeners();
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } on Error catch (e) {
      _submitLoading = false;
      notifyListeners();
      print(e.toString());
    }
  }

  Future<void> LoadTechniciangeneratorDetailsApifunction(
    homeProvider,
    BuildContext context,
    from,
    genID,
  ) async {
    try {
      final data = await ApiCalling.LoadTechnicianGeneratorDetailsAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
      );

      if (data != null) {
        if (data.error == 0) {
          _genID = genID;
          _aname = data.aname;
          _emodel = data.emodel;
          _spname = data.spname;
          _mob1 = data.mob1;
          _mob2 = data.mob2;
          _mail = data.mail;
          _cname = data.cname;
          _engineNo = data.engineNo;
          _dateOfEngineSale = data.dateOfEngineSale;
          _altNo = data.altNo;
          _btryNo = data.btryNo;
          _dgSetNo = data.dgSetNo;
          _state = data.state;
          _district = data.district;
          _address = data.address;
          _dispDate = data.dispDate;
          _cmsngDate = data.cmsngDate;
          _status = data.status;
          _complaintTypeDropdown = data.complaintTypeList ?? [];
          _complaintCategorydropdown = data.complaintCategoryList ?? [];
          _complaintDescriptionDropdown = data.complaintDescriptionList ?? [];
          if (_selectedComplaintType != null &&
              !_complaintTypeDropdown.contains(_selectedComplaintType)) {
            _selectedComplaintType = null;
            _selectedType = "";
            _selectedTypeId = "";
          }

          if (_selectedCategoryType != null &&
              !_complaintCategorydropdown.contains(_selectedCategoryType)) {
            _selectedCategoryType = null;
            _selectedCategory = "";
            _selectedCategoryId = "";
          }

          if (_selectedDescriptionType != null &&
              !_complaintDescriptionDropdown.contains(
                _selectedDescriptionType,
              )) {
            _selectedDescriptionType = null;
            _selectedDescription = "";
            _selectedDescriptionId = "";
          }
          notifyListeners();
          if (from == "Generator Details") {
            this._qrViewController!.pauseCamera();
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => Generatordetails(generatorId: _genID),
              ),
            );
          } else if (from == "Register Complaint") {
            this._qrViewController!.pauseCamera();
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => Registercomplaint()),
            );
          }
        } else if (data.error == 1) {
          toast(context, "Enter Correct ID");
        } else {}
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  Future<void> LoadgeneratorComplaintHistoryApifunction(
    homeProvider,
    BuildContext context,
    genID,
  ) async {
    try {
      final data = await ApiCalling.LoadGeneratorComplaintListAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        "All",
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _complaintList = data.list!;
            notifyListeners();
            _isLoading = false;
          } else {
            _isLoading = true;
            print("error");
          }
        } else {
          _isLoading = true;
          // SharedpreferencesService().clearPreferences();
          // toast(context, "Your Session expired, Please Login Again!");
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _isLoading = true;
        toast(context, "Something Went Wrong, Please try again!");
        print("error2");
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  Future<void> SubmitComplaintFunction(
    BuildContext context,
    homeProvider,
    genID,
    selectedTypeId,
    selectedDescriptionId,
    running_hrs,
    Complaint_Note,
  ) async {
    try {
      print("selectedTypeId:${selectedTypeId}");
      print("selectedDescriptionId:${selectedDescriptionId}");
      print("selectedDescriptionId:${selectedDescriptionId}");
      final data = await ApiCalling.SubmitGeneratorComplaintAPI(
        homeProvider.empId,
        homeProvider.session,
        selectedTypeId,
        selectedDescriptionId,
        selectedDescriptionId,
        running_hrs,
        genID,
        Complaint_Note,
      );
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, "Complaint Submitted Successfully");
            _isLoading = false;
            dispose();
            Navigator.pop(context, true);
          } else if (data.error == 1) {
            toast(context, "Something Went wrong, Please Try Again!");
          } else if (data.error == 2) {
            toast(context, "Something Went wrong, Please Try Again!");
          } else {
            toast(context, "Something Went wrong, Please Try Again!");
          }
        } else {
          toast(context, "Your session has expired, please login again!");
        }
      } else {
        toast(context, "No response from server, please try again!");
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  Future<void> TagLocationAPIFunction(
    homeProvider,
    BuildContext context,
    genID, [
    fromHere,
  ]) async {
    _submitLoading = true;
    notifyListeners();
    if (!valid(context)) {
      return;
    }
    try {
      final data = await ApiCalling.TagLocationAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        latlongs,
        _image,
      );
      print(latlongs);
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _submitLoading = false;
            notifyListeners();
            toast(context, "Location Tagged Successfully!!");
            // Navigator.pop(context);
            // if(fromHere!="Scanner"){
            //
            //   Navigator.pop(context);
            // }
            notifyListeners();
            _isLoading = false;
          } else if (data.error == 1) {
            toast(context, "Please Check Entered ID!!");
            _submitLoading = false;
            notifyListeners();
          } else {
            _isLoading = true;
            print("error");
            _submitLoading = false;
            notifyListeners();
          }
        } else {
          _isLoading = true;
          _submitLoading = false;
          notifyListeners();
          // SharedpreferencesService().clearPreferences();
          // toast(context, "Your Session expired, Please Login Again!");
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _isLoading = true;
        _submitLoading = false;
        notifyListeners();
        toast(context, "Something Went Wrong, Please try again!");
        print("error2");
      }
    } on Error catch (e) {
      _submitLoading = false;
      notifyListeners();
      print(e.toString());
    }
  }

  bool valid(context) {
    bool isValid = true;
    if (_image == null || _imagePicked == 0) {
      _imageError = "Please Add Proof";
      isValid = false;
      // notifyListeners();
    }
    if (latlongs.isEmpty) {
      toast(
        context,
        "Error in Location, Please Check your location and Try again",
      );
      isValid = false;
    }
    notifyListeners();
    return isValid;
  }

  Future<void> TagGeneraorAPIFunction(
    homeProvider,
    BuildContext context,
    genID,
    engineNumber, [
    fromHere,
  ]) async {
    try {
      _submitLoading = true;
      notifyListeners();
      final data = await ApiCalling.TagGeneratorAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        engineNumber,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _submitLoading = false;
            toast(context, "Generator Tagged Successfully!!");
            Navigator.pop(context);
            if (fromHere != "Scanner") {
              Navigator.pop(context);
            }
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder: (context) => const Gentrackerdashboard(),
              ),
              (Route<dynamic> route) {
                // Stop removing routes when Gentrackerdashboard is found
                return route.settings is MaterialPageRoute &&
                    (route.settings as MaterialPageRoute).builder(context)
                        is Gentrackerdashboard;
              },
            );
            notifyListeners();
            _isLoading = false;
          } else if (data.error == 1) {
            _submitLoading = false;
            notifyListeners();
            toast(context, data.message);
          } else if (data.error == 2) {
            _submitLoading = false;
            notifyListeners();
            toast(context, data.message);
          } else {
            _isLoading = true;
            _submitLoading = false;
            notifyListeners();
            print("error");
          }
        } else {
          _isLoading = true;
          _submitLoading = false;
          notifyListeners();
          // SharedpreferencesService().clearPreferences();
          // toast(context, "Your Session expired, Please Login Again!");
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _isLoading = true;
        _submitLoading = false;
        notifyListeners();
        toast(context, "Something Went Wrong, Please try again!");
        print("error2");
      }
    } on Error catch (e) {
      _submitLoading = false;
      notifyListeners();
      print(e.toString());
    }
  }

  Future<void> TagGeneratorCheckAPIFunction(
    homeProvider,
    BuildContext context,
    genID,
  ) async {
    try {
      _submitLoading = true;
      notifyListeners();
      final data = await ApiCalling.TagGeneratorCheckAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _submitLoading = false;
            Navigator.pop(context);
            showTagGeneratorBottomSheet(context, genID);
            notifyListeners();
            _isLoading = false;
          } else if (data.error == 1) {
            _submitLoading = false;
            notifyListeners();
            toast(context, data.message);
          } else if (data.error == 2) {
            _submitLoading = false;
            notifyListeners();
            toast(context, data.message);
          } else {
            _isLoading = true;
            _submitLoading = false;
            notifyListeners();
            print("error");
          }
        } else {
          _isLoading = true;
          _submitLoading = false;
          notifyListeners();
          // SharedpreferencesService().clearPreferences();
          // toast(context, "Your Session expired, Please Login Again!");
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _isLoading = true;
        _submitLoading = false;
        notifyListeners();
        toast(context, "Something Went Wrong, Please try again!");
        print("error2");
      }
    } on Error catch (e) {
      _submitLoading = false;
      notifyListeners();
      print(e.toString());
    }
  }

  imgFromCamera() async {
    // Capture a photo
    try {
      final XFile? galleryImage = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 50,
      );
      debugPrint("added");

      _image = File(galleryImage!.path);
      _imageName = File(galleryImage!.name);
      _imagePicked = 1;
      _imageError = null;
      notifyListeners();
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  Future<void> showTagGeneratorBottomSheet(BuildContext context, genID) {
    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: Consumer<HomescreenNotifier>(
                    builder: (context, homeProvider, child) {
                      return SingleChildScrollView(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              alignment: Alignment.topLeft,
                              child: Text(
                                "#${genID}",
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                            Container(
                              height: 48,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: AppColors.text_field_color,
                                borderRadius: BorderRadius.circular(15),
                                border:
                                    engineNoFocusNode.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: engNoController,
                                  keyboardType: TextInputType.text,
                                  focusNode: engineNoFocusNode,
                                  textCapitalization:
                                      TextCapitalization.characters,
                                  style: TextStyle(fontSize: 14),
                                  onChanged: (value) {},
                                  onTapOutside: (event) {
                                    // Handle onTapOutside
                                    FocusScope.of(context).unfocus();
                                  },
                                  decoration: InputDecoration(
                                    isDense: true,
                                    hintStyle: TextStyle(
                                      color: AppColors.grey_semi,
                                      fontWeight: FontWeight.w400,
                                      fontSize: 14,
                                    ),
                                    //contentPadding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
                                    enabledBorder: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                    hintText: 'Enter Engine Number',
                                  ),
                                ),
                              ),
                            ),
                            InkWell(
                              onTap:
                                  _submitLoading
                                      ? null
                                      : () {
                                        _submitLoading = true;
                                        notifyListeners();
                                        TagGeneraorAPIFunction(
                                          homeProvider,
                                          context,
                                          genID,
                                          engNoController.text,
                                        );
                                      },
                              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:
                                      _submitLoading
                                          ? CircularProgressIndicator.adaptive(
                                            valueColor: AlwaysStoppedAnimation(
                                              AppColors.white,
                                            ),
                                            padding: EdgeInsets.all(8.0),
                                          )
                                          : Text(
                                            "Submit",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              color: Colors.white,
                                            ),
                                          ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  // imgFromGallery(context) async {
  //   // Pick an image
  //   try {
  //     final XFile? galleryImage = await _picker.pickImage(
  //       source: ImageSource.gallery,
  //     );
  //     final bytes = (await galleryImage?.readAsBytes())?.lengthInBytes;
  //     final kb = bytes! / 1024;
  //     final mb = kb / 1024;
  //
  //     debugPrint("Jenny: bytes:$bytes, kb:$kb, mb: $mb");
  //
  //     _image = File(galleryImage!.path);
  //     _imageName = File(galleryImage!.name);
  //     _imagePicked = 1;
  //     notifyListeners();
  //     // var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
  //   } catch (e) {
  //     debugPrint("mmmm: ${e.toString()}");
  //   }
  // }
}
