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:get/get.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();
  }

  bool _isLoadingMore = false;
  bool get isLoadingMore => _isLoadingMore;

  bool _hasMoreData = true;
  bool get hasMoreData => _hasMoreData;

  int _currentPage = 1;
  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  void resetPagination() {
    _tpcAgentsList.clear();
    _currentPage = 1;
    _hasMoreData = true;
    _isLoading = false;
    _isLoadingMore = false;
    _errorMessage = null;
    notifyListeners();
  }

  Future<void> TPCAgentsListAPIFunction(
    BuildContext context,
    String mode, {
    bool append = false,
  }) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);

      if (!append) {
        _isLoading = true;
        _errorMessage = null;
        notifyListeners();
      } else {
        _isLoadingMore = true;
        notifyListeners();
      }

      final data = await ApiCalling.TPCAgentListAPI(
        provider.empId,
        provider.session,
        mode,
        _currentPage.toString(), // page number
      );
      debugPrint(
        'empId: ${provider.empId}, session: ${provider.session}, pageNumber: $_currentPage',
      );

      if (data != null && data.error == "0") {
        if (append) {
          _tpcAgentsList.addAll(data.tpcAgentList ?? []);
        } else {
          _tpcAgentsList = data.tpcAgentList ?? [];
        }

        // stop if API returns less than page size
        if (data.tpcAgentList == null || data.tpcAgentList!.length < 10) {
          _hasMoreData = false;
        }
      } else {
        if (!append) _errorMessage = "No agents found!";
        _hasMoreData = false;
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    }

    _isLoading = false;
    _isLoadingMore = false;
    notifyListeners();
  }

  Future<void> loadMore(BuildContext context, String mode) async {
    if (_isLoadingMore || !_hasMoreData) return;
    _currentPage++;
    await TPCAgentsListAPIFunction(context, mode, append: true);
  }

  Future<void> TPCAgentsIssueListAPIFunction(
    BuildContext context, {
    bool append = false,
  }) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);

      if (!append) {
        _isLoading = true;
        _errorMessage = null;
        _currentPage = 1;
        notifyListeners();
      } else {
        _isLoadingMore = true;
        notifyListeners();
      }

      final data = await ApiCalling.pendingTPCAgentIssueListAPI(
        provider.empId,
        provider.session,
        _currentPage.toString(), // page number
      );
      debugPrint(
        'empId: ${provider.empId}, session: ${provider.session}, pageNumber: $_currentPage',
      );

      if (data != null && data.error == "0") {
        if (append) {
          _tpcAgentsIssueList.addAll(data.pendingTpcIssueList ?? []);
        } else {
          _tpcAgentsIssueList = data.pendingTpcIssueList ?? [];
        }

        // if API returns less than page size, stop loading more
        if (data.pendingTpcIssueList == null ||
            data.pendingTpcIssueList!.length < 10) {
          _hasMoreData = false;
        }
      } else {
        if (!append) _errorMessage = "No issues found!";
        _hasMoreData = false;
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    }

    _isLoading = false;
    _isLoadingMore = false;
    notifyListeners();
  }

  Future<void> loadMoreIssues(BuildContext context) async {
    if (_isLoadingMore || !_hasMoreData) return;
    _currentPage++;
    await TPCAgentsIssueListAPIFunction(context, append: true);
  }

  Future<void> TPCAgentsDetailsAPIFunction(context, tpcAgentId) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.TPCAgentDetailsAPI(
        provider.empId,
        provider.session,
        tpcAgentId,
      );
      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) {}
  }

  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) {
      _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) {
      _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 (tpcMobileNumberController.text.trim().isNotEmpty &&
        tpcMobileNumberController.text.length < 10) {
      tpcMobileNumberError = "Please Enter a Valid 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()}");
    }
  }
}
