import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/services/api_calling.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../Models/TechnicianLoadNumbersResponse.dart';
import '../Utils/commonServices.dart';
import '../screens/splash.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

class Paymentdetailsprovider extends ChangeNotifier {



  List<PaymentModeList> _payment_mode_drop_down = [];
  List<Contacts> _contacts_drop_down = [];
  String _paymentModeID = "";
  String _PaymentMode = "";
  String _contactID = "";
  String _contact = "";
  String _enteredOtp = "";
  PaymentModeList? _selectPaymentModeList;
  Contacts? _selectContact;
  var _type = "";
  var _refType = "";
  var _refId = "";
  var _account_id = "";
  var _CollectionId = 0;
  var _image_picked = 0;
  final ImagePicker _picker = ImagePicker();
  File? _image;
  bool _isLoading = true;

  List<PaymentModeList> get paymentModeDropDown => _payment_mode_drop_down;
  List<Contacts> get contactsDropDown => _contacts_drop_down;
  PaymentModeList? get selectPaymentMode => _selectPaymentModeList;
  Contacts? get selectContact => _selectContact;
  String get paymentModeID => _paymentModeID;
  String get PaymentMode => _PaymentMode;
  String get contactID => _contactID;
  String get contact => _contact;
  String get enteredOtp => _enteredOtp;
  get type => _type;
  get refType => _refType;
  get refId => _refId;
  get account_id => _account_id;
  get CollectionId => _CollectionId;
  get image_picked => _image_picked;
  bool get isLoading => _isLoading;

   set enteredOtp(String value){
    _enteredOtp = value;
    notifyListeners();
  }

  set selectContact(value){
    _selectContact = value;
    _contact = value?.name;
    _contactID = value?.mob1;
    notifyListeners();

  }
  set selectPaymentMode(value){
    _selectPaymentModeList = value;
    _PaymentMode = value?.name ?? "";
    _paymentModeID = value?.id ?? "";
    notifyListeners();

  }
  set paymentModeID(value){
    _paymentModeID = value;
    notifyListeners();
  }
  set PaymentMode(value){
    _PaymentMode = value;
    notifyListeners();
  }


  set contact(value){
    _contact = value;
    notifyListeners();
  }
  set contactID(value){
    _contactID = value;
    notifyListeners();
  }

  Future<void> LoadNumbersAPI(
    BuildContext context,
    accountName,
    referenceID,
    generatorID,
  ) async {
    if (accountName == "Generator") {
      _type = "generator";
      _refType = "Complaint";
      _refId = referenceID;
    } else {
      _type = "account";
      _refType = "Account";
      _refId = referenceID;
    }
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      // print("${type}");
      final data = await ApiCalling.LoadContactsTechnicianAPI(
        homeProvider.empId,
        homeProvider.session,
        _type,
        generatorID,
        _refId,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _contacts_drop_down = data.contacts!;
            _payment_mode_drop_down = data.paymentModeList!;
            if (_selectContact != null &&
                !_contacts_drop_down.contains(_selectContact)) {
              _selectContact = null;
              _contact = "";
              _contactID = "";
            }


            if (_selectPaymentModeList != null &&
                !_payment_mode_drop_down.contains(_selectPaymentModeList)) {
              _selectPaymentModeList = null;
              _PaymentMode = "";
              _paymentModeID = "";
            }

            notifyListeners();
          } else {}
        } else {
          SharedpreferencesService().clearPreferences();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Splash()),
          );
        }
      }
    } on Error catch (e) {
      debugPrint(e.toString());
    }
  }

  Future<void> PaymentUpdateAPI(BuildContext context, reference, amount) async {
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.TechnicianUpdatepaymentAPI(
        homeProvider.empId,
        homeProvider.session,
        _refType,
        _refId,
        _paymentModeID,
        reference,
        amount,
        _contact,
        _contactID,
        _image,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _CollectionId = data.paymentCollectionId ?? 0;
            // OTPDialogue(context);
            notifyListeners();
          } else {}
        } else {
          SharedpreferencesService().clearPreferences();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Splash()),
          );
        }
      }
    } on Error catch (e) {
      debugPrint(e.toString());
    }
  }

  Future<void> OTPVerifyAPI(BuildContext context) async {
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.TechnicianPaymentOTPValidateAPI(
        homeProvider.empId,
        homeProvider.session,
        _CollectionId,
        _enteredOtp,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, data.message);
            Navigator.pop(context, true);
          } else {
            toast(context, data.message);
          }
        } else {
          SharedpreferencesService().clearPreferences();
          toast(context, data.message);
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Splash()),
          );
        }
      } else {}
    } on Error catch (e) {
      debugPrint(e.toString());
    }
  }





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

      _image = File(galleryImage!.path);
      _image_picked = 1;
      if (_image != null) {
        var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
        {
          if (file != null) {
            CheckValidations(context, reference, amount);
          }
        }
      }
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  imgFromGallery(context, reference, amount) 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);
      _image_picked = 1;
      if (_image != null) {
        var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
        {
          if (file != null) {
            CheckValidations(context, reference, amount);
          }
        }
      }
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  CheckValidations(BuildContext context, reference, amount) {
    if (_contactID == null || _contactID == "") {
      toast(context, "Select Phone Number");
    } else if (_paymentModeID == null || _paymentModeID == "") {
      toast(context, "Select Payment Mode");
    } else if (amount.isEmpty) {
      toast(context, "Enter Amount");
    } else if (_image == "" || _image == null || _image_picked == 0) {
      toast(context, "Select Attachment");
    } else {
      PaymentUpdateAPI(context, reference, amount);
    }
  }

  String _saveAgainst = "";
   String _genId = "";
   String _accountId = "";

   String get saveAgainst => _saveAgainst;
   String get genId => _genId;
   String get accountId => _accountId;

   set saveAgainst(value){
     _saveAgainst = value;
     notifyListeners();
   }
   set genId(value){
     _genId = value;
     notifyListeners();
   }
   set accountId(value){
     _accountId = value;
   }

  Future<void> AddContactAPIFunction(BuildContext context,actName,generatorID,name,designation,mobile,altMobile,telephone,email) async {

    if (actName == "Generator") {
      _saveAgainst = "Generator";
      _genId = generatorID;
    } else {
      _saveAgainst = "account";
      _accountId = generatorID;
    }
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data =   await ApiCalling.AddContactAPI(
          homeProvider.empId,
          homeProvider.session,
          _genId,
            name,designation,mobile,altMobile,telephone,email,

          _saveAgainst,
          _accountId);

          if (data != null)
            {


                if (data.sessionExists == 1) {
                  if (data.error == 0) {
                    toast(context, data.message);
                    Navigator.pop(context, true);
                  } else if (data.error == 1) {
                    toast(context, data.message);
                  }
                } else {
                  SharedpreferencesService().clearPreferences();
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => Splash()));
                }


      }
    } on Error catch (e) {
      print(e.toString());
    }
  }
}
