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/screens/LoginScreen.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 addProductPriceController = TextEditingController();
  TextEditingController addQuantityController = TextEditingController();
  TextEditingController addTotalAmountController = 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;

  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? _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;

  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 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;
    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;
    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;
    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;
    notifyListeners();
  }

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

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

  set selectedProducts(Products? value) {
    _selectedProducts = value;
    _selectedProductsId = value!.id;
    _selectedProductsValue = value!.name;
    notifyListeners();
  }

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

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

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

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

  set selectedSubLocations(SubLocations? value) {
    _selectedSubLocations = value;
    _selectedSubLocationId = value!.id!;
    _selectedSubLocationValue = value.subLocality;
    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;
    notifyListeners();
  }

  set selectedSegment(Segments? value) {
    _selectedSegments = value;
    _selectedSegmentId = value!.id!;
    _selectedSegmentValue = value.name;
    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;
    notifyListeners();
  }

  String? mailIdError = "";
  String? companynameError = "";
  String? salutationError = "";
  String? nameError = "";
  String? AlternatemobileError = "";
  String? TelephoneError = "";
  String? mobileError = "";
  String? addressError = "";
  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 = "";

  bool _isLoading = true;
  bool _submitLoading = false;

  bool get isLoading => _isLoading;

  bool get submitLoading => _submitLoading;

  set submitLoading(bool value) {
    _submitLoading = value;
    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();
    addTotalAmountController.clear();

    notifyListeners();
  }

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

  Future<void> crmAddLeadsView(context, mode) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmNewLeadsProspectsViewAPI(
        prov.empId,
        prov.session,
        mode,
      );
      if (data != null) {
        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 {}
    } catch (e, s) {}
  }

  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, s) {}
  }

  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") {
          _subLocationsList = data.subLocations!;
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  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, s) {}
  }

  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, s) {}
  }

  Future<void> crmAddNewLeadsAndProspectsAPIFunction(
    BuildContext context,
    mode,
    acc_manager_id,
    salutation_name,
    district,
    state,
    segment,
    source,
    reference,
    team,
    sub_locality,
    lead_status,
    products,
  ) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmNewLeadsProspectsSubmitAPI(
        prov.session,
        prov.empId,
        mode,
        acc_manager_id,
        salutation_name,
        companyNameController.text,
        contactPersonNameController.text,
        district,
        state,
        addressController.text,
        segment,
        source,
        reference,
        team,
        sub_locality,
        mobileController.text,
        alternateMobileController.text,
        telephoneController.text,
        customerMailIdController.text,
        designationController.text,
        lead_status,
        products,
      );
      if (data != null) {
        if (data.error == "0") {
          Navigator.pop(context, true);
          toast(context, data.message);
          resetForm();
          notifyListeners();
        } else {}
      } else {}
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

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

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

  onChangeContactPersonName(value) {
    nameError = "";
    notifyListeners();
  }

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

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

  onChangemobile(value) {
    mobileError = "";
    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();
    addProductPriceController.clear();
    addQuantityController.clear();
    addTotalAmountController.clear();

    notifyListeners();
  }

  void checkDropdownReset() {
    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().isEmpty){
    //   mailIdError = "Please enter Email Id";
    //   isValid = false;
    // }
    if(mobileController.text.trim().isEmpty){
      mobileError = "Please enter Mobile Number";
      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().isEmpty){
    //   AlternatemobileError = "";
    //   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;
    }
    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 = "";
  }
}
