import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../../Models/crmModels/crmProspectDetailsResponse.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class crmProspectDetailsProvider extends ChangeNotifier {
  bool _addContactSelected = false;
  List<Leads> _leadsList = [];
  List<Contacts> _contactsList = [];
  List<Orders> _ordersList = [];
  List<Payments> _paymentsList = [];
  AccountDetails _accountDetails = AccountDetails();

  var _transferAccount;

  bool _isLoading = false;

  bool _showMoreDetails = false;

  bool get addContactSelected => _addContactSelected;

  set addContactSelected(bool value) {
    _addContactSelected = value;
    notifyListeners();
  }

  TextEditingController nameController = TextEditingController();
  TextEditingController designationController = TextEditingController();
  TextEditingController mobileNumberController = TextEditingController();
  TextEditingController alternativeMobileController = TextEditingController();
  TextEditingController telephoneController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController editNameController = TextEditingController();
  TextEditingController editDesignationController = TextEditingController();
  TextEditingController editMobileNumberController = TextEditingController();
  TextEditingController editAlternativeMobileController =
      TextEditingController();
  TextEditingController editTelephoneController = TextEditingController();
  TextEditingController editEmailController = TextEditingController();
  TextEditingController dateController = TextEditingController();
  TextEditingController noteController = TextEditingController();

  String? _nameError;
  String? _designationError;
  String? _mobileNumError;
  String? _altMobError;
  String? _teleError;
  String? _emailError;
  String? _noteError;

  String? _editNameError;
  String? _editDesignationError;
  String? _editMobileNumError;
  String? _editAltMobError;
  String? _editTeleError;
  String? _editEmailError;

  String? _dateError;

  List<String> _headings = [];
  List<String> _subHeadings = [];
  DateTime? _date;
  String? _formattedDate;
  String? _formattedDateToSend;

  String? get formattedDateToSend => _formattedDateToSend;

  bool get showMoreDetails => _showMoreDetails;

  get showTransferAccount => _transferAccount;

  List<Leads> get leadList => _leadsList;

  List<Contacts> get contactList => _contactsList;

  List<Orders> get ordersList => _ordersList;

  List<Payments> get paymentsList => _paymentsList;

  AccountDetails get accountDetails => _accountDetails;

  String? get nameError => _nameError;

  String? get designationError => _designationError;

  String? get mobileNumError => _mobileNumError;

  String? get altMobError => _altMobError;

  String? get teleError => _teleError;

  String? get emailError => _emailError;

  String? get noteError => _noteError;

  String? get editNameError => _editNameError;

  String? get editDesignationError => _editDesignationError;

  String? get editMobileNumError => _editMobileNumError;

  String? get editAltMobError => _editAltMobError;

  String? get editTeleError => _editTeleError;

  String? get editEmailError => _editEmailError;

  String? get dateError => _dateError;

  bool get isLoading => _isLoading;

  List<String> get Headings => _headings;

  List<String> get subHeadings => _subHeadings;

  String? get formattedDate => _formattedDate;

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

  set nameError(String? value) {
    _nameError = value;
    notifyListeners();
  }

  set designationError(String? value) {
    _designationError = value;
    notifyListeners();
  }

  set mobileNumError(String? value) {
    _mobileNumError = value;
    notifyListeners();
  }

  set altMobError(String? value) {
    _altMobError = value;
    notifyListeners();
  }

  set teleError(String? value) {
    _teleError = value;
    notifyListeners();
  }

  set emailError(String? value) {
    _emailError = value;
    notifyListeners();
  }

  set noteError(String? value) {
    _noteError = value;
    notifyListeners();
  }

  set editNameError(String? value) {
    _editNameError = value;
    notifyListeners();
  }

  set editDesignationError(String? value) {
    _editDesignationError = value;
    notifyListeners();
  }

  set editMobileNumError(String? value) {
    _editMobileNumError = value;
    notifyListeners();
  }

  set editAltMobError(String? value) {
    _editAltMobError = value;
    notifyListeners();
  }

  set editTeleError(String? value) {
    _editTeleError = value;
    notifyListeners();
  }

  set editEmailError(String? value) {
    _editEmailError = value;
    notifyListeners();
  }

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  set formattedDate(String? value) {
    _formattedDate = value;
    dateController.text = _formattedDate!;
    _dateError = null;
    notifyListeners();
  }

  set dateError(value) {
    _dateError = value;
    notifyListeners();
  }

  void setDate(DateTime newDate) {
    _date = newDate;
    _formattedDate = DateFormat('d MMM yyyy').format(newDate);
    _formattedDateToSend = DateFormat('yyyy-MM-dd').format(newDate);
    dateController.text = _formattedDate!;
    _dateError = null;
    notifyListeners();
  }

  Future<void> crmProspectDetailsAPIFunction(context, leadID) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsAPI(
        HomeProv.empId,
        HomeProv.session,
        leadID,
      );
      _isLoading = true;
      notifyListeners();
      if (data != null) {
        if (data.error == "0") {
          _leadsList = data.leads!;
          _accountDetails = data.accountDetails!;
          _contactsList = data.contacts!;
          _ordersList = data.orders!;
          _paymentsList = data.payments!;
          _headings = [
            "Company Name",

            "Account Manager Name",
            "Account Created By",

            "Address",
            "State",
            "District",
            "Sub Locality",
            "Pin-code",

            "Source",
            "Reference",
            "Team",
            "Segment",
            "Account Age",
          ];
          _transferAccount = data.showTransfeLeadButton;
          _subHeadings = [
            data.accountDetails!.name ?? "-",

            data.accountDetails!.accManager ?? "-",
            data.accountDetails!.owner ?? "-",

            data.accountDetails!.address ?? "-",
            data.accountDetails!.state ?? "-",
            data.accountDetails!.district ?? "-",
            data.accountDetails!.subLocality ?? "-",
            data.accountDetails!.pincode ?? "-",

            data.accountDetails!.source ?? "-",
            data.accountDetails!.reference ?? "-",
            data.accountDetails!.team ?? "-",
            data.accountDetails!.segment ?? "-",
            "${data.accountDetails!.aage ?? "-"} days old",
          ];

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

  Future<void> crmCheckFields(context, value, type) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmCheckAccountFieldsApi(
        prov.empId,
        prov.session,
        value,
        type,
      );

      if (data != null) {
        if (data.error == "0") {
          nameError = null;
          mobileNumError = null;
          altMobError = null;
          notifyListeners();
        } else if (data.error == "1") {
          if (type == "name") {
            nameError = data.message!;
          } else if (type == 'mob1') {
            mobileNumError = data.message!;
          } else if (type == 'mob2') {
            altMobError = data.message!;
          }
          notifyListeners();
        }
      } else {
        notifyListeners();
      }
    } catch (e) {
      notifyListeners();
    }
  }

  Future<void> crmProspectDetailsAddContactAPIFunction(context, accID) async {
    try {
      if (!AddContactValidation()) {
        return;
      }
      _isLoading = true;
      notifyListeners();
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsAddAccountAPI(
        prov.empId,
        prov.session,
        nameController.text,
        accID,
        mobileNumberController.text,
        designationController.text,
        alternativeMobileController.text,
        telephoneController.text,
        emailController.text,
      );

      if (data != null) {
        if (data.error == "0") {
          Navigator.pop(context, true);
          _addContactSelected = false;
          resetAll();
          _isLoading = false;
          notifyListeners();
        } else {
          _isLoading = false;
          notifyListeners();
        }
      } else {
        _isLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> crmProspectDetailsEditContactAPIFunction(
    context,
    contactID,
    accID,
  ) async {
    try {
      if (!editContactValidation()) {
        return;
      }
      _isLoading = true;
      notifyListeners();
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsEditContactAPI(
        prov.empId,
        prov.session,
        contactID,
        editNameController.text,
        accID,
        editMobileNumberController.text,
        editAlternativeMobileController.text,
        editTelephoneController.text,
        editDesignationController.text,
        editEmailController.text,
      );

      if (data != null) {
        if (data.error == "0") {
          _isLoading = false;
          _addContactSelected = false;
          Navigator.pop(context, true);
          resetAll();
          _isLoading = false;
          notifyListeners();
        } else {
          _isLoading = false;
          notifyListeners();
        }
      } else {
        _isLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _isLoading = false;
      notifyListeners();
    }
  }

  void showDatePickerDialog(BuildContext context) {
    showCupertinoModalPopup<void>(
      context: context,
      builder:
          (BuildContext context) => Container(
            height: 250,
            padding: const EdgeInsets.only(top: 6.0),
            margin: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            color: CupertinoColors.systemBackground.resolveFrom(context),
            child: SafeArea(
              top: false,
              child: Column(
                children: [
                  Expanded(
                    flex: 2,
                    child: SizedBox(
                      height: 40,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CupertinoButton(
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                color: AppColors.app_blue,
                              ),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoButton(
                            child: Text(
                              'Done',
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                color: AppColors.app_blue,
                              ),
                            ),
                            onPressed: () {
                              setDate(_date ?? DateTime.now());
                              Navigator.pop(context);
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 4,
                    child: CupertinoDatePicker(
                      dateOrder: DatePickerDateOrder.dmy,
                      initialDateTime: _date ?? DateTime.now(),
                      minimumDate: DateTime(
                        DateTime.now().year,
                        DateTime.now().month,
                        DateTime.now().day,
                      ),
                      mode: CupertinoDatePickerMode.date,
                      use24hFormat: true,
                      showDayOfWeek: true,
                      onDateTimeChanged: (DateTime newDate) {
                        setDate(newDate);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  void onChangeName(value) {
    _nameError = "";
    notifyListeners();
  }

  void onChangeDesignation(value) {
    _designationError = "";
    notifyListeners();
  }

  void onChangeMobile(value) {
    _mobileNumError = "";
    notifyListeners();
  }

  void onChangeAltMobile(value) {
    _altMobError = "";
    notifyListeners();
  }

  void onChangeTelephone(value) {
    _teleError = "";
    notifyListeners();
  }

  void onChangeEmailId(value) {
    _emailError = "";
    notifyListeners();
  }

  void onChangeEditName(value) {
    _editNameError = "";
    notifyListeners();
  }

  void onChangeEditDesignation(value) {
    _editDesignationError = "";
    notifyListeners();
  }

  void onChangeEditMobile(value) {
    _editMobileNumError = "";
    notifyListeners();
  }

  void onChangeEditAltMobile(value) {
    _editAltMobError = "";
    notifyListeners();
  }

  void onChangeEditTelephone(value) {
    _editTeleError = "";
    notifyListeners();
  }

  void onChangeEditEmailId(value) {
    _editEmailError = "";
    notifyListeners();
  }

  void onChangeNote(value) {
    _noteError = "";
    notifyListeners();
  }

  bool AddContactValidation() {
    bool isValid = true;
    _nameError = null;
    _designationError = null;
    _mobileNumError = null;
    _altMobError = null;
    _teleError = null;
    _emailError = null;
    _noteError = null;
    if (nameController.text.trim().isEmpty) {
      _nameError = "Please Enter Name";

      isValid = false;
    }
    if (mobileNumberController.text.trim().isEmpty ||
        mobileNumberController.text.length < 10) {
      _mobileNumError = "Please Enter Mobile Number 10 Digits";
      isValid = false;
    }
    if (alternativeMobileController.text.trim().isNotEmpty) {
      if (alternativeMobileController.text.length < 10) {
        _altMobError = "Please Enter Mobile Number 10 Digits";
        isValid = false;
      }
    }
    if (mobileNumberController.text.trim() ==
        alternativeMobileController.text.trim()) {
      _altMobError =
          "Mobile Number and Alternate Mobile Number Should not be same";
      isValid = false;
    }
    if (emailController.text.isNotEmpty) {
      final RegExp emailRegex = RegExp(
        r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
      );
      isValid = emailRegex.hasMatch(emailController.text.trim());
      if (!isValid) {
        _emailError = "Please Enter Proper Email ID";
      }
    }
    _isLoading = false;
    notifyListeners();

    return isValid;
  }

  bool editContactValidation() {
    bool isValid = true;
    _editNameError = null;
    _editDesignationError = null;
    _editMobileNumError = null;
    _editAltMobError = null;
    _editTeleError = null;
    _editEmailError = null;
    _noteError = null;
    if (editNameController.text.trim().isEmpty) {
      _editNameError = "Please Enter Name";

      isValid = false;
    }
    if (editMobileNumberController.text.trim().isEmpty ||
        editMobileNumberController.text.length < 10) {
      _editMobileNumError = "Please Enter Mobile Number 10 Digits";
      isValid = false;
    }
    if (editAlternativeMobileController.text.trim().isNotEmpty) {
      if (editAlternativeMobileController.text.length < 10) {
        _editAltMobError = "Please Enter Mobile Number 10 Digits";
        isValid = false;
      }
    }
    if (editMobileNumberController.text.trim() ==
        editAlternativeMobileController.text.trim()) {
      _editAltMobError =
          "Mobile Number and Alternate Mobile Number Should not be same";
      isValid = false;
    }
    if (editEmailController.text.isNotEmpty) {
      final RegExp emailRegex = RegExp(
        r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
      );
      isValid = emailRegex.hasMatch(editEmailController.text.trim());
      if (!isValid) {
        _editEmailError = "Please Enter Proper Email ID";
      }
    }
    _isLoading = false;
    notifyListeners();

    return isValid;
  }

  void resetAll() {
    _formattedDateToSend = null;
    _formattedDate = null;
    _date = null;
    _showMoreDetails = false;
    nameController.clear();
    designationController.clear();
    mobileNumberController.clear();
    alternativeMobileController.clear();
    telephoneController.clear();
    emailController.clear();
    editNameController.clear();
    editDesignationController.clear();
    editMobileNumberController.clear();
    editAlternativeMobileController.clear();
    editTelephoneController.clear();
    editEmailController.clear();
    _nameError = "";
    _designationError = "";
    _mobileNumError = "";
    _altMobError = "";
    _teleError = "";
    _emailError = "";
    _editNameError = "";
    _editDesignationError = "";
    _editMobileNumError = "";
    _editAltMobError = "";
    _editTeleError = "";
    _editEmailError = "";
    notifyListeners();
  }
}
