import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/services/api_calling.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../../Models/financeModels/addPaymentRequestionResponse.dart';

class Requestionlistprovider extends ChangeNotifier {
  var res = {
    "requesting_purposes": [
      "Salary Advance",
      "Incentive Advance",
      "Tour Advance",
    ],
    "accounts": [
      {"id": "22", "name": "Super Admin"},
    ],
    "payment_modes": [
      {"id": "1", "name": "Cash"},
      {"id": "2", "name": "Cheque"},
      {"id": "3", "name": "RTGS"},
      {"id": "4", "name": "NEFT"},
      {"id": "5", "name": "IMPS"},
      {"id": "6", "name": "UPI"},
      {"id": "7", "name": "Online Portal"},
    ],
    "error": "0",
    "message": "Fetched Successfully",
  };

  TextEditingController reqPurposeController = TextEditingController();
  TextEditingController descController = TextEditingController();
  TextEditingController amountController = TextEditingController();
  TextEditingController bankNameController = TextEditingController();
  TextEditingController bankBranchController = TextEditingController();
  TextEditingController bankAccNumberController = TextEditingController();
  TextEditingController bankIfscController = TextEditingController();
  TextEditingController bankAcHolderController = TextEditingController();
  TextEditingController bankUpiController = TextEditingController();

  List<Accounts> _accounts = [];
  List<PaymentModes> _paymentModes = [];
  List<String> _requestingPurposes = [];
  Accounts? _selectedAccounts;
  PaymentModes? _selectedPayment;
  String? _selectReqPurpose;

  String _paymentModeId = "";
  String _paymentModeValue = "";
  String _accountId = "";
  String _reqPurpose = "";

  String? selectAccountError;
  String? reqPurposeError;
  String? descriptionError;
  String? amountError;
  String? selectPaymentError;
  String? bankNameError;
  String? bankBranchError;
  String? bankNumberError;
  String? bankIFSCError;
  String? bankHolderError;
  String? UPIError;
  String? FileError;

  bool buttonEnabled = false;

  // bool _submitClicked = false;



  var _image_picked = 0;
  final ImagePicker _picker = ImagePicker();
  File? _image;

  String get paymentModeId => _paymentModeId;

  String get paymentModeValue => _paymentModeValue;

  get image_picked => _image_picked;

  File? get imagePath => _image;

  String get accountId => _accountId;

  String get reqPurpose => _reqPurpose;

  String? get selectReqPurpose => _selectReqPurpose;

  Accounts? get selectedAccount => _selectedAccounts;

  PaymentModes? get selectedPayment => _selectedPayment;

  List<Accounts> get accounts => _accounts;

  List<PaymentModes> get paymentModes => _paymentModes;

  List<String> get requestingPurposes => _requestingPurposes;
  // bool get submitClicked => _submitClicked;

  // set submitClicked(bool value){
  //   _submitClicked = value;
  //   notifyListeners();
  // }
  set selectedAccount(Accounts? value) {
    _selectedAccounts = value;
    _accountId = value!.id!;
    selectAccountError = null;

    notifyListeners();
  }

  set selectedPayment(PaymentModes? value) {
    _selectedPayment = value;
    _paymentModeId = value!.id!;
    _paymentModeValue = value!.name!;
    selectPaymentError = null;

    notifyListeners();
  }

  set selectReqPurpose(String? value) {
    _selectReqPurpose = value;
    reqPurposeError = null;

    notifyListeners();
  }

  set paymentModeId(String value) {
    _paymentModeId = value;
    notifyListeners();
  }

  set paymentModeValue(String value) {
    _paymentModeValue = value;
    notifyListeners();
  }

  set accountId(String value) {
    _accountId = value;
    notifyListeners();
  }

  set reqPurposeId(String value) {
    _reqPurpose = value;
    notifyListeners();
  }

  imgFromCamera(context) 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;
      FileError = null;
      notifyListeners();
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  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);
      _image_picked = 1;
      FileError = null;
      notifyListeners();
      // var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  Future<void> addPaymentRequestionViewAPI(context, mode) async {
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.addPaymentRequestionViewAPI(
        homeProvider.empId,
        homeProvider.session,
        mode,
      );
      if (data != null) {
        if (data.error == "0") {
          _accounts = data.accounts!;
          _paymentModes = data.paymentModes!;
          _requestingPurposes = data.requestingPurposes!;

          if (_selectedAccounts != null &&
              !_accounts.contains(_selectedAccounts)) {
            _selectedAccounts = null;
            _accountId = "";
          }

          if (_selectedPayment != null &&
              !_paymentModes.contains(_selectedPayment)) {
            _selectedPayment = null;
            _paymentModeId = "";
          }
        } else {}
      }
    } catch (e, s) {}
  }

  Future<void> addPaymentRequestionSubmitAPI(context, mode) async {
    try {
      // _submitClicked = true;
      if (!validateForm(context, mode)) {
        // _submitClicked = false;
        return;
      }

      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.addPaymentRequestionSubmitAPI(
          homeProvider.empId,
          homeProvider.session,
          mode,
          _accountId,
         ["self","admin"].contains(mode) ?_selectReqPurpose:reqPurposeController.text,
          descController.text,
          amountController.text,
          _paymentModeId,
          bankNameController.text,
          bankBranchController.text,
          bankAccNumberController.text,
          bankIfscController.text,
          bankAcHolderController.text,
          bankUpiController.text,
          _image
      );
      if (data != null) {
        if (data['error'] == "0") {
          print(data['error']=="0");

          toast(context, "Added Successfully");
          resetForm();
          Navigator.pop(context,true);
          notifyListeners();
        } else {}
      }
    } catch (e, s) {}
  }

  void resetForm() {
    reqPurposeController.clear();
    descController.clear();
    amountController.clear();
    bankNameController.clear();
    bankBranchController.clear();
    bankAccNumberController.clear();
    bankIfscController.clear();
    bankAcHolderController.clear();
    bankUpiController.clear();

    _selectedAccounts = null;
    _selectedPayment = null;
    _selectReqPurpose = null;

    _paymentModeId = "";
    _paymentModeValue = "";
    _accountId = "";
    _reqPurpose = "";

    _image = null;
    _image_picked = 0;

    // _submitClicked = false;

    // Clear validation errors
    selectAccountError = null;
    reqPurposeError = null;
    descriptionError = null;
    amountError = null;
    selectPaymentError = null;
    bankNameError = null;
    bankBranchError = null;
    bankNumberError = null;
    bankIFSCError = null;
    bankHolderError = null;
    UPIError = null;
    FileError = null;
    buttonEnabled = false;

    notifyListeners();
  }


  bool validateForm(BuildContext context, String mode) {
    // Reset all errors
    selectAccountError = null;
    reqPurposeError = null;
    descriptionError = null;
    amountError = null;
    selectPaymentError = null;
    bankNameError = null;
    bankBranchError = null;
    bankNumberError = null;
    bankIFSCError = null;
    bankHolderError = null;
    UPIError = null;
    FileError = null;

    bool isValid = true;

    if (_selectedAccounts == null || _accountId.isEmpty) {
      selectAccountError = "Please select an account";
      isValid = false;
    }

    if (["self", "admin"].contains(mode)) {
      if (_selectReqPurpose == null || _selectReqPurpose!.isEmpty) {
        reqPurposeError = "Please select a requisition purpose";
        isValid = false;
      }
    } else {
      if (reqPurposeController.text.trim().isEmpty) {
        reqPurposeError = "Please enter a requisition purpose";
        isValid = false;
      }
    }

    if (descController.text.trim().isEmpty) {
      descriptionError = "Please enter a description";
      isValid = false;
    }

    if (amountController.text.trim().isEmpty) {
      amountError = "Please enter an amount";
      isValid = false;
    }

    if (_selectedPayment == null || _paymentModeId.isEmpty) {
      selectPaymentError = "Please select a payment mode";
      isValid = false;
    }

    if (["Cheque", "RTGS", "IMPS", "NEFT"].contains(_paymentModeValue)) {
      if (bankNameController.text.trim().isEmpty) {
        bankNameError = "Please enter bank name";
        isValid = false;
      }
      if (bankBranchController.text.trim().isEmpty) {
        bankBranchError = "Please enter bank branch";
        isValid = false;
      }
      if (bankAccNumberController.text.trim().isEmpty) {
        bankNumberError = "Please enter account number";
        isValid = false;
      }
      if (bankIfscController.text.trim().isEmpty) {
        bankIFSCError = "Please enter IFSC code";
        isValid = false;
      }
      if (bankAcHolderController.text.trim().isEmpty) {
        bankHolderError = "Please enter account holder name";
        isValid = false;
      }
    }

    if (_paymentModeValue == "UPI") {
      if (bankUpiController.text.trim().isEmpty) {
        UPIError = "Please enter UPI ID";
        isValid = false;
      }
    }

    if (_image_picked == 0) {
      FileError = "Please attach a file";
      isValid = false;
    }
    buttonEnabled = isValid;
    notifyListeners();
    return isValid;
  }

  void updateReqPupose(String value) {
    reqPurposeError = null;
    notifyListeners();
  }

  void updateDescription(String value) {
    descriptionError = null;
    notifyListeners();
  }
  void updateAmount(String value) {
    amountError = null;
    notifyListeners();
  }
  void updateBankName(String value) {
    bankNameError = null;
    notifyListeners();
  }
  void updateBankBranch(String value) {
    bankBranchError = null;
    notifyListeners();
  }
  void updateNumber(String value) {
    bankNumberError = null;
    notifyListeners();
  }
  void updateIFSC(String value) {
    bankIFSCError = null;
    notifyListeners();
  }
  void updateHolder(String value) {
    bankHolderError = null;
    notifyListeners();
  }
  void updateUPI(String value) {
    UPIError = null;
    notifyListeners();
  }

}
