import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/screens/commom/accountsListDetails.dart';
import 'package:generp/screens/finance/financeDashboard.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';

import '../../Models/commonModels/DistrictsResponse.dart';
import '../../Models/commonModels/SubLocationsResponse.dart';
import '../../Models/commonModels/commonAccountlistResponse.dart';
import '../../Models/commonModels/commonAddAccountsViewResponse.dart';

class Accountslistprovider extends ChangeNotifier {
  TextEditingController nameController = TextEditingController();
  TextEditingController mobileController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  TextEditingController bankNameController = TextEditingController();
  TextEditingController branchNameController = TextEditingController();
  TextEditingController bankIfscCotroller = TextEditingController();
  TextEditingController bankHolderNameController = TextEditingController();
  TextEditingController bankAcNumberController = TextEditingController();
  TextEditingController bankUpiController = TextEditingController();
  TextEditingController contactPersonController = TextEditingController();
  TextEditingController contectPersonDesignationController =
      TextEditingController();
  TextEditingController contectPersonAltMobController = TextEditingController();
  TextEditingController contectPersonTeleController = TextEditingController();
  TextEditingController contectPersonMailController = TextEditingController();
  TextEditingController mobileNumberController = TextEditingController();
  TextEditingController companyNameController = TextEditingController();

  TextEditingController stateSearchController = TextEditingController();
  TextEditingController districtSearchController = TextEditingController();
  TextEditingController subLocSearchController = TextEditingController();

  String? accountError;
  String? nameError;
  String? mobileError;
  String? stateError;
  String? districtError;
  String? localityError;
  String? addressError;
  String? banknameError;
  String? bankBranchError;
  String? bankIFSCError;
  String? bankHolderNameError;
  String? bankAcNumberError;
  String? upiError;
  String? contactPersonError;
  String? desigantionError;
  String? altMobError;
  String? teleError;
  String? mailError;
  String? addMoreDetailsError;

  List<States> _states = [];
  List<Districts> _districts = [];
  List<SubLocations> _subLocations = [];
  List<String> _accountTypes = [];
  List<AccountList> _accountsList = [];
  bool _isLoading = true;
  bool _hasMoreData = true;

  bool get isLoading => _isLoading;
  bool get hasMoreData => _hasMoreData;

  int _pageNum = 1;

  int get pageNum => _pageNum;

  set pageNum(value) {
    _pageNum = value;
    notifyListeners();
  }

  bool _isVisible = false;

  List<States> get states => _states;

  List<Districts> get districts => _districts;

  List<SubLocations> get subLocations => _subLocations;

  List<String> get accountTypes => _accountTypes;

  List<AccountList> get accountsList => _accountsList;

  bool get isVisible => _isVisible;

  set isVisible(bool value) {
    _isVisible = value;
    if (value == true) {
      addMoreDetailsError = null;
    }
    notifyListeners();
  }

  States? _selectedState;
  Districts? _selectedDistricts;
  SubLocations? _selectedSubLocations;
  String? _selectedAccountType;

  String? _selectedDistrictID;
  String? _selectedDistrictValue;

  String? _selectedStateID;
  String? _selectedStateValue;

  String? _selectedSubLocID;
  String? _selectedSubLocValue;

  States? get selectedState => _selectedState;

  String? get selectedStateID => _selectedStateID;

  String? get selectedStateValue => _selectedStateValue;

  Districts? get selectedDistricts => _selectedDistricts;

  String? get selectedDistrictId => _selectedDistrictID;

  String? get selectedDistrictValue => _selectedDistrictValue;

  SubLocations? get selectedSubLocations => _selectedSubLocations;

  String? get selectedSubLocID => _selectedSubLocID;

  String? get selectedSubLocValue => _selectedSubLocValue;

  String? get selectedAccountType => _selectedAccountType;

  set selectedAccountType(String? value) {
    _selectedAccountType = value;
    accountError = null;
    notifyListeners();
  }

  set selectedState(States? value) {
    _selectedState = value;
    _selectedStateID = value!.id;
    _selectedStateValue = value.name;
    stateError = null;
    notifyListeners();
  }

  set selectedDistricts(Districts? value) {
    _selectedDistricts = value;
    _selectedDistrictID = value!.id;
    _selectedDistrictValue = value.district;
    districtError = null;
    notifyListeners();
  }

  set selectedSubLocations(SubLocations? value) {
    _selectedSubLocations = value;
    _selectedSubLocID = value!.id;
    _selectedSubLocValue = value.subLocality!;
    localityError = null;
    notifyListeners();
  }

  set selectedStateID(value) {
    _selectedStateID = value;
    notifyListeners();
  }

  set selectedStateValue(value) {
    _selectedStateID = value;
    notifyListeners();
  }

  set selectedDistrictId(value) {
    _selectedDistrictID = value;
    notifyListeners();
  }

  set selectedDistrictValue(value) {
    _selectedDistrictValue = value;
    notifyListeners();
  }

  set selectedSubLocID(value) {
    _selectedSubLocID = value;
    notifyListeners();
  }

  set selectedSubLocValue(value) {
    _selectedSubLocValue = value;
    notifyListeners();
  }

  Future<void> addCommonAccountViewAPI(context) async {
    try {
      var homeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.commonAddAccountViewAPI(
        homeProv.empId,
        homeProv.session,
      );
      _accountTypes.clear();
      _states.clear();
      notifyListeners();
      if (data != null) {
        if (data.error == "0") {
          ChechkDropdownValues();
          _accountTypes = data.accountTypes!;
          _states = data.states!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> getDistrictAPI(context, stateID) async {
    try {
      var homeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      _districts.clear();
      notifyListeners();
      final data = await ApiCalling.commonAddAccountViewDistrictAPI(
        homeProv.empId,
        homeProv.session,
        stateID,
      );
      if (data != null) {
        if (data.error == "0") {
          _districts = data.districts!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> getSubLocationAPI(context, districtID) async {
    try {
      var homeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      _subLocations.clear();
      notifyListeners();
      final data = await ApiCalling.commonAddAccountViewSubLocationAPI(
        homeProv.empId,
        homeProv.session,
        districtID,
      );
      if (data != null) {
        if (data.error == "0") {
          _subLocations = data.subLocations!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> checkInputsAPI(context, type, value) async {
    try {
      var homeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.commonAddAccountCheckInputsAPI(
        homeProv.empId,
        homeProv.session,
        type,
        value,
      );
      if (data != null) {
        if (data.error == "0") {
          nameError = null;
          mobileError = null;
          notifyListeners();
        } else if (data.error == "1") {
          if (data.message?.contains("name already exists") ?? false) {
            nameError = data.message ?? "";
          } else {
            mobileError = data.message ?? "";
          }
          notifyListeners();
          // toast(context, data.message);
        }
      }
    } catch (e) {}
  }

  bool hasFilledAdditionalDetails = false;

  bool _submitClicked = false;

  bool get submitClickced => _submitClicked;

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

  Future<void> submitCommonAccountsAPI(context, from) async {
    try {
      if (!validatereceiptForm(context)) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var homeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.commonAddAccountSubmitAPI(
        homeProv.empId,
        homeProv.session,
        _selectedAccountType,
        nameController.text,
        mobileController.text,
        contectPersonAltMobController.text,
        contectPersonTeleController.text,
        contectPersonMailController.text,
        contectPersonDesignationController.text,
        addressController.text,
        _selectedStateID,
        _selectedDistrictID,
        _selectedSubLocID,
        bankNameController.text,
        branchNameController.text,
        bankIfscCotroller.text,
        bankHolderNameController.text,
        bankAcNumberController.text,
        bankUpiController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitClicked = false;
          notifyListeners();
          var res = data.id!;
          if (from == "Requesition") {
            Navigator.pop(context, res);
          } else if (from == "Dashboard") {
            print("here");

            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder: (context) => Accountslistdetails(accountID: data.id),
              ),
              (Route<dynamic> route) {
                return route.settings.arguments == 'Financedashboard';
              },
            );
          }

          resetValues();
          toast(context, data.message);
        } else if (data.error == "1") {
          _submitClicked = false;
          notifyListeners();
          toast(context, data.message);
        } else {
          _submitClicked = false;
          notifyListeners();
        }
      } else {
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  bool validateStep1() {
    accountError = null;
    nameError = null;
    mobileError = null;
    contactPersonError = null;
    bool isValid = true;
    if (_selectedAccountType == null || _selectedAccountType!.isEmpty) {
      accountError = "Please select an Account";
      isValid = false;
    }
    if (nameController.text.trim().isEmpty) {
      nameError = "Please Enter a Name";
      isValid = false;
    }
    if (mobileController.text.trim().isNotEmpty &&
        mobileController.text.length < 10) {
      mobileError = "Mobile Number should be 10 digits";
      isValid = false;
    }
    if (mobileController.text.trim().isEmpty) {
      mobileError = "Please Enter Mobile Number";
      isValid = false;
    }
    if (contactPersonController.text.trim().isEmpty) {
      contactPersonError = "Please Enter Contact Person Name";
      isValid = false;
    }
    _submitClicked = false;
    notifyListeners();
    return isValid;
  }

  bool validateStep2() {
    stateError = null;
    districtError = null;
    localityError = null;
    addressError = null;
    bool isValid = true;
    // if (_selectedState == null || _selectedStateID!.isEmpty) {
    //   stateError = "Please select a State";
    //   isValid = false;
    // }
    // if (_selectedDistricts == null || _selectedDistrictID!.isEmpty) {
    //   districtError = "Please select a District";
    //   isValid = false;
    // }
    // if (_selectedSubLocations == null || _selectedSubLocID!.isEmpty) {
    //   localityError = "Please select a Locality";
    //   isValid = false;
    // }
    // if (addressController.text.trim().isEmpty) {
    //   addressError = "Please Enter an Address";
    //   isValid = false;
    // }
    _submitClicked = false;
    notifyListeners();
    return isValid;
  }

  bool validateStep3() {
    banknameError = null;
    bankBranchError = null;
    bankIFSCError = null;
    bankHolderNameError = null;
    bankAcNumberError = null;
    upiError = null;
    bool isValid = true;
    // if (bankNameController.text
    //     .trim()
    //     .isEmpty) {
    //   banknameError = "Please Enter a Bank Name";
    //   isValid = false;
    // }
    //
    // if (branchNameController.text
    //     .trim()
    //     .isEmpty) {
    //   bankBranchError = "Please Enter Branch Name";
    //   isValid = false;
    // }
    // if (bankIfscCotroller.text
    //     .trim()
    //     .isEmpty) {
    //   bankIFSCError = "Please Enter Bank IFSC";
    //   isValid = false;
    // }
    // if (bankHolderNameController.text
    //     .trim()
    //     .isEmpty) {
    //   bankHolderNameError = "Please Enter Account Holder Name";
    //   isValid = false;
    // }
    // if (bankAcNumberController.text
    //     .trim()
    //     .isEmpty) {
    //   bankAcNumberError = "Please Enter Bank Account Number";
    //   isValid = false;
    // }
    // if (bankUpiController.text
    //     .trim()
    //     .isEmpty) {
    //   upiError = "Please Enter UPI ID";
    //   isValid = false;
    // }
    _submitClicked = false;
    notifyListeners();
    return isValid;
  }

  bool validateStep4() {
    bool isValid = true;
    //   if (contectPersonDesignationController.text
    //       .trim()
    //       .isEmpty) {
    //     desigantionError = "Please Enter Designation";
    //     isValid = false;
    //   }
    //   if (contectPersonAltMobController.text
    //       .trim()
    //       .isEmpty) {
    //     altMobError = "Please Enter Mobile Number";
    //     isValid = false;
    //   }
    //
    // }

    // if (contectPersonTeleController.text.trim().isEmpty) {
    //   teleError= "Please Enter Telephone"; isValid = false;
    // }
    // if (contectPersonMailController.text.trim().isEmpty) {
    //   teleError= "Please Enter"; isValid = false;
    // }
    _submitClicked = false;
    notifyListeners();

    return isValid;
  }

  bool validatereceiptForm(BuildContext context) {
    accountError = null;
    nameError = null;
    mobileError = null;
    stateError = null;
    districtError = null;
    localityError = null;
    addressError = null;
    banknameError = null;
    bankBranchError = null;
    bankIFSCError = null;
    bankHolderNameError = null;
    bankAcNumberError = null;
    upiError = null;
    contactPersonError = null;
    desigantionError = null;
    altMobError = null;
    teleError = null;
    mailError = null;
    addMoreDetailsError = null;
    bool isValid = true;
    if (_selectedAccountType == null || _selectedAccountType!.isEmpty) {
      accountError = "Please select an Account";
      isValid = false;
    }
    if (nameController.text.trim().isEmpty) {
      nameError = "Please Enter a Name";
      isValid = false;
    }
    if (mobileController.text.trim().isEmpty) {
      mobileError = "Please Enter Mobile Number";
      isValid = false;
    }
    if (contactPersonController.text.trim().isEmpty) {
      contactPersonError = "Please Enter Contact Person Name";
      isValid = false;
    }
    //
    //
    // if (!_isVisible && !hasFilledAdditionalDetails) {
    //   addMoreDetailsError = "Please Add More Details to Continue";
    //   isValid = false;
    // }
    // if(_isVisible) {
    //
    //   if (_selectedState == null || _selectedStateID!.isEmpty) {
    //     stateError = "Please select a State";
    //     isValid = false;
    //   }
    //   if (_selectedDistricts == null || _selectedDistrictID!.isEmpty) {
    //     districtError = "Please select a District";
    //     isValid = false;
    //   }
    //   if (_selectedSubLocations == null || _selectedSubLocID!.isEmpty) {
    //     localityError = "Please select a Locality";
    //     isValid = false;
    //   }
    //   if (addressController.text.trim().isEmpty) {
    //     addressError = "Please Enter an Address";
    //     isValid = false;
    //   }
    //   if (bankNameController.text
    //       .trim()
    //       .isEmpty) {
    //     banknameError = "Please Enter a Bank Name";
    //     isValid = false;
    //   }
    //
    //   if (branchNameController.text
    //       .trim()
    //       .isEmpty) {
    //     bankBranchError = "Please Enter Branch Name";
    //     isValid = false;
    //   }
    //   if (bankIfscCotroller.text
    //       .trim()
    //       .isEmpty) {
    //     bankIFSCError = "Please Enter Bank IFSC";
    //     isValid = false;
    //   }
    //   if (bankHolderNameController.text
    //       .trim()
    //       .isEmpty) {
    //     bankHolderNameError = "Please Enter Account Holder Name";
    //     isValid = false;
    //   }
    //   if (bankAcNumberController.text
    //       .trim()
    //       .isEmpty) {
    //     bankAcNumberError = "Please Enter Bank Account Number";
    //     isValid = false;
    //   }
    //   if (bankUpiController.text
    //       .trim()
    //       .isEmpty) {
    //     upiError = "Please Enter UPI ID";
    //     isValid = false;
    //   }
    //   if (contactPersonController.text
    //       .trim()
    //       .isEmpty) {
    //     contactPersonError = "Please Enter Contact Person Name";
    //     isValid = false;
    //   }
    //   if (contectPersonDesignationController.text
    //       .trim()
    //       .isEmpty) {
    //     desigantionError = "Please Enter Designation";
    //     isValid = false;
    //   }
    //   if (contectPersonAltMobController.text
    //       .trim()
    //       .isEmpty) {
    //     altMobError = "Please Enter Mobile Number";
    //     isValid = false;
    //   }
    //
    // }

    // if (contectPersonTeleController.text.trim().isEmpty) {
    //   teleError= "Please Enter Telephone"; isValid = false;
    // }
    // if (contectPersonMailController.text.trim().isEmpty) {
    //   teleError= "Please Enter"; isValid = false;
    // }
    _submitClicked = false;
    notifyListeners();
    return isValid;
  }

  void updateName(String value) {
    nameError = null;
    notifyListeners();
  }

  void updateMobile(String value) {
    mobileError = null;
    notifyListeners();
  }

  void updateAddress(String value) {
    addressError = null;
    notifyListeners();
  }

  void updateBankName(String value) {
    banknameError = null;

    notifyListeners();
  }

  void updateBankBranch(String value) {
    bankBranchError = null;

    notifyListeners();
  }

  void updateIFSC(String value) {
    bankIFSCError = null;

    notifyListeners();
  }

  void updateHolder(String value) {
    bankHolderNameError = null;

    notifyListeners();
  }

  void updateNumber(String value) {
    bankAcNumberError = null;

    notifyListeners();
  }

  void updateUPI(String value) {
    upiError = null;

    notifyListeners();
  }

  void updateContactPerson(String value) {
    contactPersonError = null;

    notifyListeners();
  }

  void updateDesignation(String value) {
    desigantionError = null;

    notifyListeners();
  }

  void updateAltMobile(String value) {
    altMobError = null;

    notifyListeners();
  }

  void updateTeleMobile(String value) {
    teleError = null;

    notifyListeners();
  }

  void updateMail(String value) {
    mailError = null;

    notifyListeners();
  }

  void onChangedMobileNum(value) {
    notifyListeners();
  }

  void onChangedCompanyName(value) {
    notifyListeners();
  }

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  // Common Account list  provider
  Future<void> commonAccountListAPIFunction(
    BuildContext context, {
    bool append = false,
  }) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);

      if (!append) {
        // Fresh load / Refresh
        _accountsList.clear();
        _pageNum = 1;
        _hasMoreData = true;
        _isLoading = true;
      } else {
        _isLoading = true;
      }

      notifyListeners();

      final data = await ApiCalling.commonAccountListAPI(
        prov.empId,
        prov.session,
        _pageNum,
        companyNameController.text,
        mobileNumberController.text,
      );
      debugPrint(
        'empId: ${prov.empId}, session: ${prov.session}, pageNumber: $_pageNum',
      );

      if (data != null && data.error == "0") {
        if (data.accountList != null) {
          if (append) {
            // Append with deduplication
            final existingIds = _accountsList.map((e) => e.id).toSet();
            final newItems =
                data.accountList!
                    .where((item) => !existingIds.contains(item.id))
                    .toList();
            _accountsList.addAll(newItems);
          } else {
            _accountsList = data.accountList!;
          }

          // Check if we still have more records
          _hasMoreData = data.accountList!.length >= 10;
          if (_hasMoreData) _pageNum++;
        }
      }
    } catch (e) {
      debugPrint("Error in commonAccountListAPIFunction: $e");
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  resetValues() {
    print("rv");
    _selectedAccountType = null;
    _selectedState = null;
    _selectedDistricts = null;
    _selectedSubLocations = null;
    _selectedStateID = null;
    _selectedStateValue = null;
    _selectedDistrictID = null;
    _selectedDistrictValue = null;
    _selectedSubLocID = null;
    _selectedSubLocValue = null;

    _isVisible = false;
    stateSearchController.clear();
    districtSearchController.clear();
    subLocSearchController.clear();
    nameController.clear();
    mobileController.clear();
    addressController.clear();
    bankNameController.clear();
    branchNameController.clear();
    bankIfscCotroller.clear();
    bankHolderNameController.clear();
    bankAcNumberController.clear();
    bankUpiController.clear();
    contactPersonController.clear();
    contectPersonDesignationController.clear();
    contectPersonAltMobController.clear();
    contectPersonTeleController.clear();
    contectPersonMailController.clear();
    mobileNumberController.clear();
    companyNameController.clear();
    accountError = null;
    nameError = null;
    mobileError = null;
    stateError = null;
    districtError = null;
    localityError = null;
    addressError = null;
    banknameError = null;
    bankBranchError = null;
    bankIFSCError = null;
    bankHolderNameError = null;
    bankAcNumberError = null;
    upiError = null;
    contactPersonError = null;
    desigantionError = null;
    altMobError = null;
    teleError = null;
    mailError = null;
    addMoreDetailsError = null;

    ChechkDropdownValues();
    notifyListeners();
  }

  void ChechkDropdownValues() {
    if (!_accountTypes.contains(_selectedAccountType) &&
        _selectedAccountType != null) {
      _selectedAccountType = null;
    }
    if (!_states.contains(_selectedState) && _selectedState != null) {
      _selectedStateID = null;
      _selectedStateValue = null;
    }
    if (!_districts.contains(_selectedDistricts) &&
        _selectedDistricts != null) {
      _selectedDistrictID = null;
      _selectedDistrictValue = null;
    }
    if (!_subLocations.contains(_selectedSubLocations) &&
        _selectedSubLocations != null) {
      _selectedSubLocID = null;
      _selectedSubLocValue = null;
    }
    notifyListeners();
  }
}
