import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/screens/genTracker/GeneratorDetails.dart';
import 'package:generp/screens/genTracker/RegisterComplaint.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: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 '../screens/splash.dart';
import 'HomeScreenNotifier.dart';

class Generatordetailsprovider extends ChangeNotifier {

  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? _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 _title = "";
  String _subTitle = "";
  bool _isLoading = false;
  String? _scannedGenID;

  LatLng startLocation = const LatLng(17.439112226708446, 78.43292499146135);
  LatLng? currentLocationLatLng;
  String latlongs = "";
  List<ComplaintTypeList> _complaintTypeDropdown = [];
  List<ComplaintCategoryList> _complaintCategorydropdown = [];
  List<ComplaintDescriptionList> _complaintDescriptionDropdown = [];

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

  String? _selectedType;
  String? _selectedTypeId;

  String? _selectedCategory;
  String? _selectedCategoryId;

  String? _selectedDescription;
  String? _selectedDescriptionId;

  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 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;

  bool get isLoading => _isLoading;

  bool get hasPermission => _hasPermission;

  bool get hasLocationPermission => _hasLocationPermission;
  String? get scannedGenID => _scannedGenID;
  QRViewController? get qrViewController => _qrViewController;

   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;
  }

  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;
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Generatordetails(generatorId: scanData.code,)),
        );
      } else if (from == "Register Complaint") {
        _genID = scanData.code;
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Registercomplaint()),
        );
      } else if (from == "Tag Location") {
        _genID = scanData.code;
        print(scanData.code);
        TagLocationAPIFunction(HomeProvider, context, scanData.code,"Scanner");
      } else if (from == "Tag Generator") {
        _genID = scanData.code;
        print(scanData.code);
        showTagGeneratorBottomSheet(context,_genID);
        // TagGeneraorAPIFunction(HomeProvider, context, scanData.code);
      }
    });
  }

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

      if (data != null) {
        if (data.error == 0) {
          _genID = data.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 = "";
          }
          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 {}

        notifyListeners();
      }
    } on Error catch (e) {
      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 = "";
          }

          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 {}
        notifyListeners();
      }
    } 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 {
    try {
      final data = await ApiCalling.TagLocationAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        latlongs,
      );
      print(latlongs);
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            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!!");
          } 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> TagGeneraorAPIFunction(
    homeProvider,
    BuildContext context,
    genID,engineNumber,[fromHere]
  ) async {
    try {
      final data = await ApiCalling.TagGeneratorAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        engineNumber,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, "Generator 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!!");
          }else if (data.error == 2) {
            toast(context, data.message);
          }
          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> 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: Consumer2<Generatordetailsprovider, HomescreenNotifier>(
                    builder: (context, provider, 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(20),
                                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(
                                      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: () {

                                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(30.0),
                                ),
                                child: Center(
                                  child: Text(
                                    "Submit",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
