import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/crmModels/crmProspectDetailsAddLeadsResponse.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';

class Addprospectleadsprovider extends ChangeNotifier {

  TextEditingController searchController = TextEditingController();

  List<Products>  _leadProductsList = [];
  List<Employees> _employeeList = [];
  List<String>    _statusList = [];
  Employees? _selectedEmployees;
  String? _selectedStatus;
  String? _selectedEmployeeId;
  String? _selectedEmployeeValue;
  Products? _selectedProducts;

  List<TextEditingController> editProductPriceControllers = [];
  List<TextEditingController> editQuantityControllers = [];
  List<TextEditingController> editTotalAmountControllers = [];
  List<String?> _selectedProductIds = [];
  List<String?> _selectedValues = [];
  bool _submitLoading = false;

  List<Products> get leadProductsList => _leadProductsList;
  Products? get selectedProducts => _selectedProducts;
  List<String?> get selectedProductIds => _selectedProductIds;
  List<String?> get selectedValues => _selectedValues;
  bool get submitLoading => _submitLoading;
  List<Employees> get employeeList => _employeeList;
  List<String> get statusList => _statusList;
  Employees? get selectedEmployee => _selectedEmployees;
  String? get selectedStatus => _selectedStatus;
  String? get selectedEmployeeId => _selectedEmployeeId;
  String? get selectedEmployeeValue => _selectedEmployeeValue;


  set selectedEmployee(Employees? value){
    _selectedEmployees = value;
    _selectedEmployeeId = value!.id!;
    _selectedEmployeeValue = value!.name!;
    notifyListeners();
  }

  set selectedStatus(String? value){
    _selectedStatus = value;
    notifyListeners();
  }

  set selectedEmployeeId(String? value){
    _selectedEmployeeId = value;
    notifyListeners();
  }
  set selectedEmployeeValue(String? value){
    _selectedEmployeeValue = value;
    notifyListeners();
  }

  set selectedProducts(Products? value) {
    _selectedProducts = value;
    notifyListeners();
  }

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

  void initializeForm(BuildContext context) {
    // Clear existing controllers
    editProductPriceControllers.clear();
    editQuantityControllers.clear();
    editTotalAmountControllers.clear();
    _selectedProductIds.clear();
    _selectedValues.clear();

    // Add one empty row if the list is empty
    if (_leadProductsList.isEmpty) {
      editAddNewRow();
    }

    notifyListeners();
  }

  void editAddNewRow() {
    editProductPriceControllers.add(TextEditingController());
    editQuantityControllers.add(TextEditingController());
    editTotalAmountControllers.add(TextEditingController());
    _selectedProductIds.add(null);
    _selectedValues.add(null);
    notifyListeners();
  }

  void editRemoveRow(int index) {
    editProductPriceControllers[index].dispose();
    editQuantityControllers[index].dispose();
    editTotalAmountControllers[index].dispose();
    editProductPriceControllers.removeAt(index);
    editQuantityControllers.removeAt(index);
    editTotalAmountControllers.removeAt(index);
    _selectedProductIds.removeAt(index);
    _selectedValues.removeAt(index);
    notifyListeners();
  }

  void updateSelectedProductIds(int index, Products value) {
    _selectedProductIds[index] = value.id;
    _selectedValues[index] = value.name;
    notifyListeners();
  }

  void updateTotalAmount(int index) {
    final price = double.tryParse(editProductPriceControllers[index].text) ?? 0;
    final qty = int.tryParse(editQuantityControllers[index].text) ?? 0;
    editTotalAmountControllers[index].text = (price * qty).toString();
    notifyListeners();
  }

  List<Map<String, String>> getFormData() {
    final List<Map<String, String>> insertData = [];
    for (int i = 0; i < editProductPriceControllers.length; i++) {
      if (_selectedProductIds[i] != null) {
        final rowData = {
          "product_id": _selectedProductIds[i]!,
          "price": editProductPriceControllers[i].text,
          "qty": editQuantityControllers[i].text,
          "net_price":editTotalAmountControllers[i].text
        };
        insertData.add(rowData);
      }
    }
    return insertData;
  }

  Future<void> crmProspectDetailsAddLeadsViewAPIFunction(BuildContext context, String mode) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsAddLeadViewAPI(prov.empId, prov.session, mode);
      if (data != null && data.error == "0") {
       _leadProductsList =  data.products!;
       _employeeList  =  data.employees!;
       _statusList  =  data.status!;
        notifyListeners();
      }
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

  Future<void> crmProspectDetailsAddLeadsSubmitAPIFunction(BuildContext context,mode, account_id, acc_manager_id, products, lead_status) async {
    try {
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsAddLeadSubmitAPI(prov.empId, prov.session, mode, account_id, acc_manager_id, products, lead_status);
      if (data != null && data.error == "0") {
        resetForm();
        Navigator.pop(context,true);
        toast(context, data.message);
        notifyListeners();
      }
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

  void submitForm(BuildContext context,mode,accId,empID,status) async {
    submitLoading = true;
    final insertedData = getFormData();
    print("Form Data: $insertedData");

    // crmProspectDetailsAddLeadsSubmitAPIFunction(context,mode,accId,empID,insertedData,status);
    submitLoading = false;
  }

  void resetForm() {
    searchController.clear();
    editProductPriceControllers.clear();
    editQuantityControllers.clear();
    editTotalAmountControllers.clear();
    _selectedProductIds.clear();
    _selectedValues.clear();
    _leadProductsList.clear();
    _selectedStatus = null;
    _selectedEmployeeId = null;
    _selectedEmployeeValue = null;
    checkDropDownReset();
    notifyListeners();
  }
  checkDropDownReset(){
    if(!_employeeList.contains(_selectedEmployees)&&_selectedEmployees!=null){
      _selectedEmployeeId = null;
      _selectedEmployeeValue = null;
    }
    notifyListeners();
  }


}