import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Models/ordersModels/TPCListResponse.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/PendingTPCAgentListResponse.dart';
import '../../Models/ordersModels/TPCAgentDetailsResponse.dart';
import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Tpcagentsprovider extends ChangeNotifier{
  bool _submitClicked = false;
  bool _showMoreDetails = false;

  TextEditingController tpcNameController = TextEditingController();
  TextEditingController tpcMobileNumberController = TextEditingController();
  TextEditingController tpcBankNameController = TextEditingController();
  TextEditingController tpcBankBeneficiaryNameController = TextEditingController();
  TextEditingController tpcBankAccountNumberController = TextEditingController();
  TextEditingController tpcBankIFSCController = TextEditingController();
  TextEditingController tpcNoteController = TextEditingController();

  TextEditingController tpcPaymentModeController = TextEditingController();
  TextEditingController tpcPaymentReferenceNoController = TextEditingController();
  TextEditingController orderTpcFeedbackController = TextEditingController();

  String? tpcNameError = "";
  String? tpcMobileNumberError = "";
  String? tpcBankNameError = "";
  String? tpcBankBeneficiaryNameError = "";
  String? tpcBankAccountNumberError = "";
  String? tpcBankIFSCError = "";
  String? tpcNoteError = "";
  String? imageError = "";

  String? tpcPaymentModeError = "";
  String? tpcPaymentReferenceNoError = "";
  String? orderTpcFeedbackError = "";

  List<TpcAgentList> _tpcAgentsList = [];
  List<PendingTpcIssueList> _tpcAgentsIssueList = [];
  TpcAgentDetails _tpcAgentDetails = TpcAgentDetails();
  List<TpcRequestedAmounts> _tpcRequestedAmounts = [];
  List<String> _headings = [];
  List<String> _subHeadings = [];

  bool _isLoading = false;
  var _image_picked = 0;
  final ImagePicker _picker = ImagePicker();

  File? _image;
  File? _imageName;

  bool get submitClicked => _submitClicked;
  bool get showMoreDetails => _showMoreDetails;
  List<String> get Headings => _headings;

  List<String> get subHeadings => _subHeadings;
  List<TpcAgentList> get tpcAgentsList => _tpcAgentsList;
  List<PendingTpcIssueList> get tpcAgentsIssueList => _tpcAgentsIssueList;
  TpcAgentDetails get TPCAgentsDetails => _tpcAgentDetails;
  List<TpcRequestedAmounts> get TPCRequestedAmounts => _tpcRequestedAmounts;
  bool get isLoading => _isLoading;
  get image_picked => _image_picked;

  File? get imagePath => _imageName;

  File? get imageFilePath => _image;

  get imagePicked => _image_picked;

  set submitClicked(bool value){
    _submitClicked = value;
    notifyListeners();
  }

  set showMoreDetails(bool value){
    _showMoreDetails = value;
    notifyListeners();
  }

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

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

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


  Future<void> TPCAgentsListAPIFunction(context, mode,) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.TPCAgentListAPI(
        provider.empId,
        provider.session,
        mode,
      );
      if (data != null) {
        _tpcAgentsList.clear();
        _isLoading = true;
        notifyListeners();
        if (data.error == "0") {
          _tpcAgentsList = data.tpcAgentList!;
          _isLoading = false;
        } else {
          _isLoading = false;
        }
        notifyListeners();
      }
    } catch (e, s) {}
  }

  Future<void> TPCAgentsIssueListAPIFunction(context,) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.pendingTPCAgentIssueListAPI(
        provider.empId,
        provider.session,
      );
      if (data != null) {
        _tpcAgentsIssueList.clear();
        _isLoading = true;
        notifyListeners();
        if (data.error == "0") {
          _tpcAgentsIssueList = data.pendingTpcIssueList!;
          _isLoading = false;

          notifyListeners();
        } else {
          _isLoading = false;
        }
        notifyListeners();
      }
    } catch (e, s) {}
  }

  Future<void> TPCAgentsDetailsAPIFunction(context, tpc_agent_id) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.TPCAgentDetailsAPI(
        provider.empId,
        provider.session,
        tpc_agent_id,
      );
      if (data != null) {
        _tpcRequestedAmounts.clear();
        _isLoading = true;
        notifyListeners();
        if (data.error == "0") {
          _tpcAgentDetails = data.tpcAgentDetails!;
          _tpcRequestedAmounts = data.tpcRequestedAmounts!;
          _isLoading = false;
          _headings = ["Agent Name",
            "Mobile Number",
            "TPC Agent Bank Name",
            "Bank Beneficiary Name",
            "Bank Account No",
            "Bank IFSC Code",
            "ID Proof",
            "Order Received Date",
            "Created Date",
            "Note",
            ];
          _subHeadings = [
            _tpcAgentDetails.name??"-",
            _tpcAgentDetails.mobileNumber??"-",
            _tpcAgentDetails.bankName??"-",
            _tpcAgentDetails.bankBeneficiaryName??"-",
            _tpcAgentDetails.bankAccountNo??"-",
            _tpcAgentDetails.bankIfscCode??"-",
            _tpcAgentDetails.idProofViewFileName??"-",
            _tpcAgentDetails.createdDatetime??"-",
            _tpcAgentDetails.note??"-"
          ];

          notifyListeners();
        } else {
          _isLoading = false;
        }
        notifyListeners();
      }
    } catch (e, s) {}
  }

  Future<void> TPCAgentsIssueApprovalAPIFunction(context, orderID,) async {
    try {
      if (!validateApproveForm(context)) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.TpcIssueListApprovalAPI(
        provider.empId,
        provider.session,
          tpcPaymentModeController.text,
          tpcPaymentReferenceNoController.text,
          orderID,
          orderTpcFeedbackController.text,
          _image
      );
      if (data != null) {

        if (data.error == "0") {
          _submitClicked = false;
          toast(context, "Submitted Successfully");
          resetAll();
          resetApprovalForm();
          Navigator.pop(context, true);
          notifyListeners();
        }else{
          _submitClicked = false;
          notifyListeners();
        }
      }else{
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e, s) {

    _submitClicked = false;
    notifyListeners();

    }
  }

  Future<void> addTPCAgentAPIFunction(context) async {
    try {
      if (!validateAddTPCAgentForm(context)) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersAddTPCAgentAPI(
        provider.empId,
        provider.session,
          tpcNameController.text,
          tpcMobileNumberController.text,
          tpcBankNameController.text,
          tpcBankBeneficiaryNameController.text,
          tpcBankAccountNumberController.text,
          tpcBankIFSCController.text,
          tpcNoteController.text,
        _image

      );
      if (data != null) {

        if (data.error == "0") {
          _submitClicked = false;
          toast(context, "Submitted Successfully");
          resetAll();
          resetAddTPCAgentForm();
          Navigator.pop(context, true);
          notifyListeners();
        }else{
          _submitClicked = false;
          notifyListeners();
        }
      }else{
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e, s) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  bool validateAddTPCAgentForm(BuildContext context) {
    // Reset all errors
    tpcNameError = null;
    tpcMobileNumberError = null;
    tpcBankNameError = null;
    tpcBankBeneficiaryNameError = null;
    tpcBankAccountNumberError = null;
    tpcBankIFSCError = null;
    tpcNoteError = null;

    bool isValid = true;

    if(tpcNameController.text.trim().isEmpty){
      tpcNameError = "Please Enter Your Name";
      isValid = false;
    }
    if(tpcMobileNumberController.text.trim().isEmpty){
      tpcMobileNumberError = "PLease Enter Your Mobile Number";
      isValid = false;
    }
    if(_image_picked==0){
      imageError = "Please select ID Proof";

      isValid = false;
    }
    if(tpcBankNameController.text.trim().isEmpty){
      tpcBankNameError = "Please Enter Bank Name";
      isValid = false;
    }
    if(tpcBankBeneficiaryNameController.text.trim().isEmpty){
      tpcBankBeneficiaryNameError = "Please Enter Beneficiery Name";
      isValid = false;
    }
    if(tpcBankAccountNumberController.text.trim().isEmpty){
      tpcBankAccountNumberError = "Please Enter Account Number";
      isValid = false;
    }
    if(tpcBankIFSCController.text.trim().isEmpty){
      tpcBankIFSCError = "Please Enter IFSC";
      isValid = false;
    }
    _submitClicked = false;

    notifyListeners();
    return isValid;
  }

  bool validateApproveForm(BuildContext context) {
    // Reset all errors
    tpcPaymentModeError = null;
    tpcPaymentReferenceNoError = null;
    orderTpcFeedbackError = null;

    bool isValid = true;

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

      if (tpcPaymentReferenceNoController.text.trim().isEmpty) {
        tpcPaymentReferenceNoError = "Please enter a description";
        isValid = false;
      }
      if (orderTpcFeedbackController.text.trim().isEmpty) {
        orderTpcFeedbackError = "Please enter a description";
        isValid = false;
      }
    _submitClicked = false;
    notifyListeners();
    return isValid;
  }

  void onChangeTPCPayment(value){
    tpcPaymentModeError = "";
    notifyListeners();
  }

  void onChangeTPCPaymentReference(value){
    tpcPaymentReferenceNoError = "";
    notifyListeners();
  }

  void onChangeTpcFeedback(value){
    orderTpcFeedbackError = "";
    notifyListeners();
  }

  void onChangetpcName(value){
    tpcNameError = "";

    notifyListeners();
  }
  void onChangetpcMobileNumber(value){
    tpcMobileNumberError = "";

    notifyListeners();
  }
  void onChangetpcBankName(value){
    tpcBankNameError = "";

    notifyListeners();
  }
  void onChangetpcBankBeneficiaryName(value){
    tpcBankBeneficiaryNameError = "";

    notifyListeners();
  }
  void onChangetpcBankAccountNumber(value){
    tpcBankAccountNumberError = "";

    notifyListeners();
  }
  void onChangetpcBankIFSC(value){
    tpcBankIFSCError = "";

    notifyListeners();
  }
  void onChangetpcNote(value){
    tpcNoteError = "";
    notifyListeners();
  }

  void resetAddTPCAgentForm() {
    tpcNameController.clear();
    tpcMobileNumberController.clear();
    tpcBankNameController.clear();
    tpcBankBeneficiaryNameController.clear();
    tpcBankAccountNumberController.clear();
    tpcBankIFSCController.clear();
    tpcNoteController.clear();
    tpcPaymentModeController.clear();
    tpcPaymentReferenceNoController.clear();
    orderTpcFeedbackController.clear();
    tpcNameError = "";
    tpcMobileNumberError = "";
    tpcBankNameError = "";
    tpcBankBeneficiaryNameError = "";
    tpcBankAccountNumberError = "";
    tpcBankIFSCError = "";
    tpcNoteError = "";
    _image = null;
    _imageName = null;
    imageError = null;
    _image_picked = 0;
    notifyListeners();
  }

  void resetApprovalForm() {
    tpcPaymentModeController.clear();
    tpcPaymentReferenceNoController.clear();
    orderTpcFeedbackController.clear();
    tpcPaymentModeError = "";
    tpcPaymentReferenceNoError = "";
    orderTpcFeedbackError = "";
    _image = null;
    _imageName = null;
    imageError = null;
    _image_picked = 0;
    notifyListeners();
  }

  void resetAll(){
    tpcNameController.clear();
    tpcMobileNumberController.clear();
    tpcBankNameController.clear();
    tpcBankBeneficiaryNameController.clear();
    tpcBankAccountNumberController.clear();
    tpcBankIFSCController.clear();
    tpcNoteController.clear();
    tpcPaymentModeController.clear();
    tpcPaymentReferenceNoController.clear();
    orderTpcFeedbackController.clear();
    tpcPaymentModeError = "";
    tpcPaymentReferenceNoError = "";
    orderTpcFeedbackError = "";
    tpcNameError = "";
    tpcMobileNumberError = "";
    tpcBankNameError = "";
    tpcBankBeneficiaryNameError = "";
    tpcBankAccountNumberError = "";
    tpcBankIFSCError = "";
    tpcNoteError = "";
    _image = null;
    _imageName = null;
    _image_picked = 0;
    imageError = null;
    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);
      _imageName = File(galleryImage!.name);
      _image_picked = 1;
      imageError = 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);
      _imageName = File(galleryImage!.name);
      _image_picked = 1;
      imageError = null;
      notifyListeners();
      // var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }
}