import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_download_manager/flutter_download_manager.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:generp/Models/crmModels/crmSelectedProductDetailsResponse.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/screens/crm/LeadDetailsByMode.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../Models/crmModels/GetDistrictOnStateResponse.dart';
import '../../Models/crmModels/GetSegmentOnTeamResponse.dart';
import '../../Models/crmModels/GetSourceOnReferenceResponse.dart';
import '../../Models/crmModels/GetSubLocOnDistrictResponse.dart';
import '../../Models/crmModels/crmNewLeadsProspectsViewResponse.dart';
import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Addnewleadsandprospectsprovider extends ChangeNotifier {
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
      FlutterLocalNotificationsPlugin();
  static const platform = MethodChannel('in.webgrid.generp/download');

  final GlobalKey webViewKey = GlobalKey();
  var dl = DownloadManager();

  TextEditingController sourceSearchController = TextEditingController();
  TextEditingController referenceSearchController = TextEditingController();
  TextEditingController teamSearchController = TextEditingController();
  TextEditingController segmentSearchController = TextEditingController();
  TextEditingController productSearchController = TextEditingController();

  TextEditingController addProductPriceController = TextEditingController();
  TextEditingController addQuantityController = TextEditingController();
  TextEditingController addTotalAmountController = TextEditingController();
  TextEditingController remarkController = TextEditingController();

  TextEditingController companyNameController = TextEditingController();
  TextEditingController contactPersonNameController = TextEditingController();
  TextEditingController customerMailIdController = TextEditingController();
  TextEditingController mobileController = TextEditingController();
  TextEditingController alternateMobileController = TextEditingController();
  TextEditingController telephoneController = TextEditingController();
  TextEditingController designationController = TextEditingController();

  TextEditingController addressController = TextEditingController();
  TextEditingController taxesController = TextEditingController();
  TextEditingController SpecialNoteController = TextEditingController();
  TextEditingController forController = TextEditingController();
  TextEditingController paymentTermsController = TextEditingController();
  List<Map<String, dynamic>> _productRows = []; // For backend
  List<Map<String, dynamic>> get productRows => _productRows;



  ProductsData? _selectedProductsDeatilsData;
  List<Employees> _employeesList = [];
  List<Sources> _sourcesList = [];
  List<Teams> _teamsList = [];
  List<States> _statesList = [];
  List<Products> _productsList = [];
  List<String> _salutationList = [];

  List<Districts> _districtsList = [];
  List<SubLocations> _subLocationsList = [];
  List<References> _referencesList = [];
  List<Segments> _segmentsList = [];

  Employees? _selectedEmployees;
  String? _selectedEmployeesId;
  String? _selectedEmployeesValue;
  Sources? _selectedSources;
  String? _selectedSourcesId;
  String? _selectedSourcesValue;
  Teams? _selectedTeams;
  String? _selectedTeamsId;
  String? _selectedTeamsValue;
  States? _selectedStates;
  String? _selectedStatesId;
  String? _selectedStatesValue;
  Products? _selectedProducts;
  String? _selectedProductsRemarks;
  String? _selectedProductsId;
  String? _selectedProductsValue;
  String? _selectedSalutation;
  Districts? _selectedDistricts;
  SubLocations? _selectedSubLocations;
  References? _selectedReferences;
  Segments? _selectedSegments;
  String? _selectedDistrictId;
  String? _selectedDistrictValue;
  String? _selectedSubLocationId;
  String? _selectedSubLocationValue;
  String? _selectedReferenceId;
  String? _selectedReferenceValue;
  String? _selectedSegmentId;
  String? _selectedSegmentValue;
  String? _selectedLeadStatus;

  ProductsData? get selectedProductsDetailsData => _selectedProductsDeatilsData;

  String? get selectedLeadStatus => _selectedLeadStatus;

  List<Employees> get employeesList => _employeesList;

  List<Sources> get sourcesList => _sourcesList;

  List<Teams> get teamsList => _teamsList;

  List<States> get statesList => _statesList;

  List<Products> get productsList => _productsList;

  List<String> get salutationList => _salutationList;

  Employees? get selectedEmployees => _selectedEmployees;

  String? get selectedEmployeesId => _selectedEmployeesId;

  String? get selectedEmployeesValue => _selectedEmployeesValue;

  Sources? get selectedSources => _selectedSources;

  String? get selectedSourcesId => _selectedSourcesId;

  String? get selectedSourcesValue => _selectedSourcesValue;

  Teams? get selectedTeams => _selectedTeams;

  String? get selectedTeamsId => _selectedTeamsId;

  String? get selectedTeamsValue => _selectedTeamsValue;

  States? get selectedStates => _selectedStates;

  String? get selectedStatesId => _selectedStatesId;

  String? get selectedStatesValue => _selectedStatesValue;

  Products? get selectedProducts => _selectedProducts;

  String? get selectedProductsRemarks => _selectedProductsRemarks;

  String? get selectedProductsId => _selectedProductsId;

  String? get selectedProductsValue => _selectedProductsValue;

  String? get selectedSalutation => _selectedSalutation;

  List<Districts> get districtsList => _districtsList;

  List<SubLocations> get subLocationsList => _subLocationsList;

  List<References> get referencesList => _referencesList;

  List<Segments> get segmentsList => _segmentsList;

  References? get selectedReference => _selectedReferences;

  Segments? get selectedSegment => _selectedSegments;

  Districts? get selectedDistricts => _selectedDistricts;

  SubLocations? get selectedSubLocations => _selectedSubLocations;

  String? get selectedDistrictId => _selectedDistrictId;

  String? get selectedDistrictValue => _selectedDistrictValue;

  String? get selectedSubLocationId => _selectedSubLocationId;

  String? get selectedSubLocationValue => _selectedSubLocationValue;

  String? get selectedReferenceId => _selectedReferenceId;

  String? get selectedReferenceValue => _selectedReferenceValue;

  String? get selectedSegmentId => _selectedSegmentId;

  String? get selectedSegmentValue => _selectedSegmentValue;

  set selectedLeadStatus(String? value) {
    _selectedLeadStatus = value;
    leadStatusError = null;
    notifyListeners();
  }

  set selectedEmployees(Employees? value) {
    _selectedEmployees = value;
    _selectedEmployeesId = value!.id;
    _selectedEmployeesValue = value.name;
    notifyListeners();
  }

  set selectedEmployeesId(String? value) {
    _selectedEmployeesId = value;
    notifyListeners();
  }

  set selectedEmployeesValue(String? value) {
    _selectedEmployeesValue = value;
    notifyListeners();
  }

  set selectedSources(Sources? value) {
    _selectedSources = value;
    _selectedSourcesId = value!.id;
    _selectedSourcesValue = value.name;
    sourceError = null;
    notifyListeners();
  }

  set selectedSourcesId(String? value) {
    _selectedSourcesId = value;
    notifyListeners();
  }

  set selectedSourcesValue(String? value) {
    _selectedSourcesValue = value;
    notifyListeners();
  }

  set selectedTeams(Teams? value) {
    _selectedTeams = value;
    _selectedTeamsId = value!.id;
    _selectedTeamsValue = value.name;
    teamsError = null;
    notifyListeners();
  }

  set selectedTeamsId(String? value) {
    _selectedTeamsId = value;
    notifyListeners();
  }

  set selectedTeamsValue(String? value) {
    _selectedTeamsValue = value;
    notifyListeners();
  }

  set selectedStates(States? value) {
    _selectedStates = value;
    _selectedStatesId = value!.id;
    _selectedStatesValue = value.name;
    statesError = null;
    notifyListeners();
  }

  set selectedStatesId(String? value) {
    _selectedStatesId = value;
    notifyListeners();
  }

  set selectedStatesValue(String? value) {
    _selectedStatesValue = value;
    notifyListeners();
  }

  set selectedProducts(Products? value) {
    _selectedProducts = value;
    if (value != null) {
      _selectedProductsId = value.id;
      _selectedProductsValue = value.name;
      _selectedProductsRemarks = value.remarks;
    }

    notifyListeners();
  }

  set selectedProductsId(String? value) {
    _selectedProductsId = value;
    notifyListeners();
  }

  set selectedProductsValue(String? value) {
    _selectedProductsValue = value;
    notifyListeners();
  }

  set selectedProductsRemark(String? value) {
    _selectedProductsRemarks = value;
    notifyListeners();
  }

  set selectedSalutation(String? value) {
    _selectedSalutation = value;
    salutationError = null;
    notifyListeners();
  }

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

  set selectedSubLocations(SubLocations? value) {
    _selectedSubLocations = value;
    _selectedSubLocationId = value!.id!;
    _selectedSubLocationValue = value.subLocality;
    subLocError = null;
    notifyListeners();
  }

  set selectedDistrictId(String? value) {
    _selectedDistrictId = value;
    notifyListeners();
  }

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

  set selectedSubLocationId(String? value) {
    _selectedSubLocationId = value;
    notifyListeners();
  }

  set selectedSubLocationValue(String? value) {
    _selectedSubLocationValue = value;
    notifyListeners();
  }

  set selectedReference(References? value) {
    _selectedReferences = value;
    _selectedReferenceId = value!.id!;
    _selectedReferenceValue = value.name;
    referenceError = null;
    notifyListeners();
  }

  set selectedSegment(Segments? value) {
    _selectedSegments = value;
    _selectedSegmentId = value!.id!;
    _selectedSegmentValue = value.name;
    segmentsError = null;
    notifyListeners();
  }

  set selectedReferenceId(String? value) {
    _selectedReferenceId = value;
    notifyListeners();
  }

  set selectedReferenceValue(String? value) {
    _selectedReferenceValue = value;
    notifyListeners();
  }

  set selectedSegmentId(String? value) {
    _selectedSegmentId = value;
    notifyListeners();
  }

  set selectedSegmentValue(String? value) {
    _selectedSegmentValue = value;
    notifyListeners();
  }

  set productRows(value) {
    _productRows = value;
    productsEmptyError = "";
    notifyListeners();
  }

  String getJsonEncodedProducts() {
    return jsonEncode(productRows);
  }

  String? mailIdError = "";
  String? companynameError = "";
  String? salutationError = "";
  String? nameError = "";
  String? AlternatemobileError = "";
  String? TelephoneError = "";
  String? mobileError = "";
  String? addressError = "";
  String? productsEmptyError = "";
  String? designationError = "";
  String? taxesError = "";
  String? SpecialNoteError = "";
  String? forError = "";
  String? paymentTermsError = "";
  String? sourceError = "";
  String? referenceError = "";
  String? teamsError = "";
  String? segmentsError = "";
  String? statesError = "";
  String? districtsError = "";
  String? subLocError = "";
  String? leadStatusError = "";

  final bool _isLoading = true;
  bool _submitLoading = false;

  bool get isLoading => _isLoading;

  bool get submitLoading => _submitLoading;

  set submitLoading(bool value) {
    _submitLoading = value;
    notifyListeners();
  }

  // New method to update an existing product
  void updateProduct(int index, Map<String, dynamic> updatedProduct) {
    productRows[index] = updatedProduct;
    notifyListeners();
  }

  //   provider.productRows.add({
  //   "product_id": provider.selectedProductsId!,
  //   "price": provider.addProductPriceController.text,
  //   "qty": provider.addQuantityController.text,
  //   "net_price": provider.addTotalAmountController.text,
  // });
  // Existing method to add a new product
  void addProduct(Map<String, dynamic> product) {
    productRows.add(product);
    notifyListeners();
  }

  void prefillProductForEdit(int index) {
    final product = productRows[index];
    selectedProducts = productsList.firstWhere(
      (p) => p.id == product['product_id'],
      orElse: () => Products(id: '', name: 'Unknown'),
    );
    selectedProductsId = product['product_id'];
    selectedProductsValue = selectedProducts?.name;
    addProductPriceController.text = product['price'] ?? '';
    addQuantityController.text = product['qty'] ?? '';
    addTotalAmountController.text = product['net_price'] ?? '';
    remarkController.text = product['remarks'] ?? '';
    notifyListeners();
  }

  void addEditUpdateTotalAmount(value) {
    final price = double.tryParse(addProductPriceController.text) ?? 0;
    final qty = int.tryParse(addQuantityController.text) ?? 0;
    addTotalAmountController.text = (price * qty).toString();
    notifyListeners();
  }

  void addInitializeForm(BuildContext context) {
    addProductPriceController.clear();
    addQuantityController.clear();
    remarkController.clear();
    addTotalAmountController.clear();

    notifyListeners();
  }

  void updateSelectedProductIds(int index, value) {
    notifyListeners();
  }

  Future<void> crmAddLeadsView(context) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmNewLeadsProspectsViewAPI(
        prov.empId,
        prov.session,
      );
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == "0") {
            _employeesList = data.employees!;
            _sourcesList = data.sources!;
            _teamsList = data.teams!;
            _statesList = data.states!;
            _productsList = data.products!;
            _salutationList = data.salutation!;
            notifyListeners();
          } else {}
        } else {}
      } else {
        sessionDoesNotExist(context);
      }
    } catch (e) {}
  }


  /// check phone number and name existence on server
  Future<bool> checkAccountFieldExistence(
      BuildContext context, {
        required String type,   // e.g. "mob1", "mob2", "name"
        required String typeValue,
      }) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);

      final res = await ApiCalling.crmCheckAccountFieldsApi(
        prov.empId,
        prov.session,
        typeValue,
        type,
      );

      if (res != null) {
        if (res.error == "0") {
          // ✅ No error -> field available
          debugPrint("✅ $type is available: $typeValue");
          return true;
        } else {
          // ❌ Field already exists
          debugPrint("⚠️ $type already exists: $typeValue");
          return false;
        }
      } else {
        debugPrint("❌ Null Response while checking $type");
        return false;
      }
    } catch (e, s) {
      debugPrint("❌ Error in checkAccountFieldExistence: $e \n$s");
      return false;
    }
  }


  Future<void> crmLeadListDistrictsOnStateAPIFunction(
    context,
    mode,
    stateID,
  ) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmDistrictsOnStateAPI(
        prov.empId,
        prov.session,
        stateID,
      );
      if (data != null) {
        if (data.error == "0") {
          _districtsList = data.districts!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> crmLeadListSubLocOnDistrictAPIFunction(
    context,
    mode,
    districtID,
  ) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmSubLocOnDistrictAPI(
        prov.empId,
        prov.session,
        districtID,
      );
      if (data != null) {
        if (data.error == "0") {
          print("Auto");
          _subLocationsList = data.subLocations!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> crmLeadListSourceOnReferenceAPIFunction(
    context,
    mode,
    sourceID,
  ) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmLeadListSourceOnReferenceAPI(
        prov.empId,
        prov.session,
        sourceID,
      );
      if (data != null) {
        if (data.error == "0") {
          _referencesList = data.references!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> crmLeadListSegmentOnTeamAPIFunction(
    context,
    mode,
    teamID,
  ) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmLeadListSegmentOnTeamAPI(
        prov.empId,
        prov.session,
        teamID,
      );
      if (data != null) {
        if (data.error == "0") {
          _segmentsList = data.segments!;
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> crmAddNewLeadsAndProspectsAPIFunction(
    BuildContext context,
    mode,
    accManagerId,
    salutationName,
    district,
    state,
    segment,
    source,
    reference,
    team,
    subLocality,
    leadStatus,
    products,
  ) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmNewLeadsProspectsSubmitAPI(
        prov.session,
        prov.empId,
        mode,
        accManagerId,
        salutationName,
        companyNameController.text,
        contactPersonNameController.text,
        district,
        state,
        addressController.text,
        segment,
        source,
        reference,
        team,
        subLocality,
        mobileController.text,
        alternateMobileController.text,
        telephoneController.text,
        customerMailIdController.text,
        designationController.text,
        leadStatus,
        products,
      );
      if (data != null) {
        if (data.error == "0") {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(
              builder:
                  (context) => LeadDetailsByMode(
                    mode: "executive",
                    pageTitleName: "Lead Details",
                    leadId: data.leadId ?? "-",
                  ),
              settings: RouteSettings(name: "LeadDetailsByMode"),
            ),
            (Route<dynamic> route) {
              return route.settings.name == 'CrmdashboardScreen';
            },
          );
          toast(context, data.message);
          resetForm();
          notifyListeners();
        } else {}
      } else {}
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

  Future<void> crmSelectedProductDetailsApiFunction(
    BuildContext context,
    String productId,
  ) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmSelectedProductDetailsApi(
        prov.empId,
        prov.session,
        productId,
      );

      if (data != null && data.error == "0") {
        _selectedProductsDeatilsData = data.productsData!;
        addProductPriceController.text = data.productsData!.price!;
        remarkController.text = data.productsData!.remarks!;
        notifyListeners();
      }
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

  onChangemailId(value) {
    mailIdError = "";
    notifyListeners();
  }

  onChangeCompanyName(value) {
    companynameError = "";
    notifyListeners();
  }




  onChangeAlternatemobile(value) {
    AlternatemobileError = "";
    notifyListeners();
  }

  onChangeTelephone(value) {
    TelephoneError = "";
    notifyListeners();
  }

  Future<void> onChangeContactPersonName(BuildContext context, String value) async {
    nameError = "";
    if (value.isEmpty) {
      nameError = "Name cannot be empty";
    } else if (value.length < 3) {
      nameError = "Name must be at least 3 characters";
    } else {
      final exists = await checkAccountFieldExistence(
        context,
        type: "name",
        typeValue: value,
      );
      if (!exists) {
        nameError = "Name already exists";
      } else {
        nameError = null;
      }
    }
    notifyListeners();
  }


  Future<void> onChangemobile(BuildContext context, String value) async {
    mobileError = "";
    if (value.isEmpty) {
      mobileError = "Mobile number cannot be empty";
    } else if (value.length != 10) {
      mobileError = "Mobile number must be 10 digits";
    } else {
      // ✅ Call API to check existence
      final exists = await checkAccountFieldExistence(
        context,
        type: "mob1", // or "mob2" depending on which mobile field you are validating
        typeValue: value,
      );
      if (!exists) {
        mobileError = "Mobile number already exists";
      } else {
        mobileError = null;
      }
    }
    notifyListeners();
  }


  onChangeaddress(value) {
    addressError = "";
    notifyListeners();
  }

  onChangedesignation(value) {
    designationError = "";
    notifyListeners();
  }

  onChangetaxes(value) {
    taxesError = "";
    notifyListeners();
  }

  onChangeSpecialNote(value) {
    SpecialNoteError = "";
    notifyListeners();
  }

  onChangefor(value) {
    forError = "";
    notifyListeners();
  }

  onChangepaymentTerms(value) {
    paymentTermsError = "";
    notifyListeners();
  }

  void resetForm() {
    checkDropdownReset();
    _productRows.clear();
    remarkController.clear();
    sourceSearchController.clear();
    referenceSearchController.clear();
    teamSearchController.clear();
    segmentSearchController.clear();
    addProductPriceController.clear();
    addQuantityController.clear();
    addTotalAmountController.clear();
    addTotalAmountController.clear();
    addProductPriceController.clear();
    addQuantityController.clear();
    addTotalAmountController.clear();

    companyNameController.clear();
    contactPersonNameController.clear();
    customerMailIdController.clear();
    mobileController.clear();
    alternateMobileController.clear();
    telephoneController.clear();
    designationController.clear();

    addressController.clear();
    taxesController.clear();
    _productRows = [];
    _selectedProductsDeatilsData = null;
    _selectedEmployees = null;
    _selectedEmployeesId = null;
    _selectedEmployeesValue = null;
    _selectedSources = null;
    _selectedSourcesId = null;
    _selectedSourcesValue = null;
    _selectedTeams = null;
    _selectedTeamsId = null;
    _selectedTeamsValue = null;
    _selectedStates = null;
    _selectedStatesId = null;
    _selectedStatesValue = null;
    _selectedProducts = null;
    _selectedProductsRemarks = null;
    _selectedProductsId = null;
    _selectedProductsValue = null;
    _selectedSalutation = null;
    _selectedDistricts = null;
    _selectedSubLocations = null;
    _selectedReferences = null;
    _selectedSegments = null;
    _selectedDistrictId = null;
    _selectedDistrictValue = null;
    _selectedSubLocationId = null;
    _selectedSubLocationValue = null;
    _selectedReferenceId = null;
    _selectedReferenceValue = null;
    _selectedSegmentId = null;
    _selectedSegmentValue = null;
    _selectedLeadStatus = null;
    mailIdError = "";
    companynameError = "";
    salutationError = "";
    nameError = "";
    AlternatemobileError = "";
    TelephoneError = "";
    mobileError = "";
    addressError = "";
    designationError = "";
    taxesError = "";
    SpecialNoteError = "";
    forError = "";
    paymentTermsError = "";
    sourceError = "";
    referenceError = "";
    teamsError = "";
    segmentsError = "";
    statesError = "";
    districtsError = "";
    subLocError = "";
    leadStatusError = "";
    productsEmptyError = "";
    notifyListeners();
  }

  void checkDropdownReset() {
    if (!_productsList.contains(_selectedProducts) &&
        _selectedProducts != null) {
      _selectedProductsId = null;
      _selectedProductsValue = null;
      _selectedProductsRemarks = null;
    }
    if (!_employeesList.contains(_selectedEmployees) &&
        _selectedEmployees != null) {
      _selectedEmployeesId = null;
      _selectedEmployeesValue = null;
    }
    if (!_sourcesList.contains(_selectedSources) && _selectedSources != null) {
      _selectedSourcesId = null;
      _selectedSourcesValue = null;
    }
    if (!_referencesList.contains(_selectedReferences) &&
        _selectedReferences != null) {
      _selectedReferenceId = null;
      _selectedReferenceValue = null;
    }
    if (!_segmentsList.contains(_selectedSegments) &&
        _selectedSegments != null) {
      _selectedTeamsId = null;
      _selectedTeamsValue = null;
    }
    if (!_teamsList.contains(_selectedTeams) && _selectedTeams != null) {
      _selectedSegmentId = null;
      _selectedSegmentValue = null;
    }
    if (!_districtsList.contains(_selectedDistricts) &&
        _selectedDistricts != null) {
      _selectedDistrictId = null;
      _selectedDistrictValue = null;
    }
    if (!_statesList.contains(_selectedStates) && _selectedStates != null) {
      _selectedStatesId = null;
      _selectedStatesValue = null;
    }
    if (!_subLocationsList.contains(_selectedSubLocations) &&
        _selectedSubLocations != null) {
      _selectedSubLocationId = null;
      _selectedSubLocationValue = null;
    }
    notifyListeners();
  }

  bool validateStep1() {
    bool isValid = true;

    if (_selectedSalutation == null || _selectedSalutation == '') {
      isValid = false;
      salutationError = "Please Select Salutation";
    }

    if (companyNameController.text.trim().isEmpty) {
      companynameError = "Please Enter Company Name";
      isValid = false;
    }
    if (contactPersonNameController.text.trim().isEmpty) {
      nameError = "Please Enter Name";
      isValid = false;
    }
    if (customerMailIdController.text.trim().isNotEmpty &&
        !RegExp(r'\S+@\S+\.\S+').hasMatch(customerMailIdController.text)) {
      mailIdError = "Please enter a proper Email ID";
      isValid = false;
    }
    if (mobileController.text.trim().isEmpty) {
      mobileError = "Please enter Mobile Number";
      isValid = false;
    } else {
      if (mobileController.text.length < 10) {
        mobileError = "Please enter 10 digits";
        isValid = false;
      }
    }

    // if(designationController.text.trim().isEmpty){
    //   designationError = "Please enter Designation";
    //   isValid = false;
    // }

    notifyListeners();
    return isValid;
  }

  bool validateStep2() {
    bool isValid = true;
    if (alternateMobileController.text.trim().isNotEmpty &&
        alternateMobileController.text.length < 10) {
      AlternatemobileError = "Please enter 10 digits";
      isValid = false;
    }
    // if(telephoneController.text.trim().isEmpty){
    //   isValid = false;
    //
    // }

    if (_selectedSources == null || _selectedSourcesId!.isEmpty) {
      sourceError = "Please Select Source";
      isValid = false;
    }
    if (_selectedReferences == null || _selectedReferenceId!.isEmpty) {
      referenceError = "Please Select Reference";
      isValid = false;
    }
    if (_selectedTeams == null || _selectedTeamsId!.isEmpty) {
      teamsError = "Please Select Team";
      isValid = false;
    }
    if (_selectedSegments == null || _selectedSegmentId!.isEmpty) {
      segmentsError = "Please Select Segement";
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

  bool validateStep3() {
    bool isValid = true;
    if (_selectedStates == null || _selectedStatesId!.isEmpty) {
      statesError = "Please Select State";
      isValid = false;
    }
    if (_selectedDistricts == null || _selectedDistrictId!.isEmpty) {
      districtsError = "Please Select District";
      isValid = false;
    }
    // if(_selectedSubLocations==null||_selectedSubLocationId!.isEmpty){
    //   subLocError = "Please Select Sub Location";
    //   isValid = false;
    // }
    if (_selectedLeadStatus == null || _selectedLeadStatus!.isEmpty) {
      leadStatusError = "Please Select Lead Status";
      isValid = false;
    }
    if (addressController.text.trim().isEmpty) {
      addressError = "Please Enter address";
      isValid = false;
    }
    if (productRows.isEmpty || _productRows.isEmpty) {
      productsEmptyError = "Please Add min. one Product";
      isValid = false;
    }
    notifyListeners();
    return isValid;
  }

  resetForm2() {
    customerMailIdController.clear();
    mobileController.clear();
    addressController.clear();
    taxesController.clear();
    SpecialNoteController.clear();
    forController.clear();
    paymentTermsController.clear();
    mailIdError = "";
    mobileError = "";
    addressError = "";
    designationError = "";
    taxesError = "";
    SpecialNoteError = "";
    forError = "";
    paymentTermsError = "";
  }
}
