// import 'package:flutter/foundation.dart';
// import 'package:flutter/material.dart';
// import 'package:generp/Notifiers/HomeScreenNotifier.dart';
// import 'package:generp/services/api_calling.dart';
// import 'package:provider/provider.dart';
//
// import '../../Models/crmModels/crmLeadDetailsEditProductsViewResponse.dart';
//
// class Editproductlistprovider extends ChangeNotifier{
//
//   List<Products> _productsList = [];
//   List<LeadProducts> _leadProductsList = [];
//
//   Products? _selectedProducts;
//
//
//   List<TextEditingController> editProductPriceControllers = [];
//   List<TextEditingController> editQuantityControllers = [];
//   List<TextEditingController> editTotalAmountControllers = [];
//
//   List<String?> _selectedProductIds = [];
//   List<String?> _selectedProductValues = [];
//
//   List<Map<String, String>> _insertData = [];
//   bool _submitLoading = false;
//
//   bool get submitLoading => _submitLoading;
//
//   List<Products> get productsList => _productsList;
//   List<LeadProducts> get leadProductsList => _leadProductsList;
//
//   Products? get selectedProducts => _selectedProducts;
//
//   List<String?> get selectedProductIds => _selectedProductIds;
//   List<String?> get selectedProductValues => _selectedProductValues;
//
//   set selectedProducts(Products? value){
//     _selectedProducts = value;
//     notifyListeners();
//   }
//
//   set selectedProductIds(List<String?> value){
//     _selectedProductIds = value;
//     notifyListeners();
//   }
//   set selectedProductValues(List<String?> value){
//     _selectedProductValues = value;
//     notifyListeners();
//   }
//
//   void updateSelectedProductIds(int index, Products? value) {
//     _selectedProducts = value!;
//
//     _selectedProductIds[index] = value!.id;
//     print(_selectedProductIds[index]);
//     notifyListeners();
//   }
//
//   set submitLoading(bool value){
//     _submitLoading = value;
//     notifyListeners();
//   }
//
//   void editAddNewRow() {
//     editProductPriceControllers.add(TextEditingController());
//     editQuantityControllers.add(TextEditingController());
//     editTotalAmountControllers.add(TextEditingController());
//     _selectedProductIds.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);
//     notifyListeners();
//   }
//   //
//   //
//   List<Map<String, String>> getFormData() {
//     _insertData = [];
//     for (int i = 0; i < _productsList.length; i++) {
//       final rowData = {
//         "product_id": _productsList[i]!.id.toString(),
//         "price": editQuantityControllers[i]!.text.toString(),
//         "qty": editTotalAmountControllers[i]!.text.toString(),
//       };
//       _insertData.add(rowData);
//     }
//     notifyListeners();
//     return _insertData;
//   }
//
//   Future<void> crmLeadDetailsEditProductsViewAPIFunction(context,leadID) async {
//     try{
//       final prov = Provider.of<HomescreenNotifier>(context,listen: false);
//       final data = await ApiCalling.crmLeadDetailsEditProductsViewAPI(prov.empId, prov.session, leadID);
//       if(data!=null){
//         if(data.error=="0"){
//           _leadProductsList = data.leadProducts!;
//           _productsList= data.products!;
//           notifyListeners();
//         }else{
//
//         }
//       }else{
//
//       }
//     }catch(e,s){
//
//     }
//   }
//
//   resetForm(){
//
//   }
// }
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/crmModels/crmSelectedProductDetailsResponse.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';
import '../../Models/crmModels/crmLeadDetailsEditProductsViewResponse.dart';
import '../../screens/LoginScreen.dart';
import 'crmLeadDetailsProvider.dart';

class Editproductlistprovider extends ChangeNotifier {
  TextEditingController addEditProductPriceController = TextEditingController();
  TextEditingController addEditQuantityController = TextEditingController();
  TextEditingController addEditTotalAmountController = TextEditingController();
  List<Products> _productsList = [];
  List<LeadProducts> _leadProductsList = [];
  Products? _selectedProducts;
  ProductsData? _selectedProductsDeatilsData;
  String? _selectedAddEditProductId;
  String? _selectedAddEditProductName;
  List<TextEditingController> editProductPriceControllers = [];
  List<TextEditingController> editQuantityControllers = [];
  List<TextEditingController> editTotalAmountControllers = [];
  List<String?> _selectedProductIds = [];
  List<String?> _selectedValues = [];
  bool _submitLoading = false;
  String? qtyError;
  String? priceError;
  String? productError;
  List<Products> get productsList => _productsList;

  List<LeadProducts> get leadProductsList => _leadProductsList;

  ProductsData? get selectedProductsDetailsData => _selectedProductsDeatilsData;

  Products? get selectedProducts => _selectedProducts;

  String? get selectedAddEditProductId => _selectedAddEditProductId;

  String? get selectedAddEditProductName => _selectedAddEditProductName;

  List<String?> get selectedProductIds => _selectedProductIds;

  List<String?> get selectedValues => _selectedValues;

  bool get submitLoading => _submitLoading;

  set selectedProducts(Products? value) {
    _selectedProducts = value;
    _selectedAddEditProductId = value!.id!;
    _selectedAddEditProductName = value.name;
    productError = null;
    notifyListeners();
  }

  set selectedAddEditProductId(String? value) {
    _selectedAddEditProductId = value;
    notifyListeners();
  }

  set selectedAddEditProductName(String? value) {
    _selectedAddEditProductName = 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();

    // Initialize controllers for each lead product
    for (var product in _leadProductsList) {
      editProductPriceControllers.add(
        TextEditingController(text: product.price?.toString() ?? ''),
      );
      editQuantityControllers.add(
        TextEditingController(text: product.qty?.toString() ?? ''),
      );
      editTotalAmountControllers.add(
        TextEditingController(
          text:
              (double.parse(product.price?.toString() ?? '0') *
                      int.parse(product.qty?.toString() ?? '0'))
                  .toString(),
        ),
      );
      _selectedProductIds.add(product.productId);
      _selectedValues.add(product.productName);
    }

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

  void addEditUpdateTotalAmount() {
    final price = double.tryParse(addEditProductPriceController.text) ?? 0;
    final qty = int.tryParse(addEditQuantityController.text) ?? 0;
    addEditTotalAmountController.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,
        };
        insertData.add(rowData);
      }
    }
    return insertData;
  }

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

      if (data != null){
        if(data.sessionExists==1){
          if( data.error == "0") {
            _leadProductsList = data.leadProducts ?? [];
            _productsList = data.products ?? [];
            notifyListeners();
          }
        }else{
          sessionDoesNotExist(context);
        }

      }

    } 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!;
        addEditProductPriceController.text=  data.productsData!.price!;
        notifyListeners();
      }
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }




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

  Future<void> crmLeadDetailsAddEditProductsSubmitAPIFunction(
    BuildContext context,
  mode,
    String leadID,
    type,
    leadProductId,
    productId,
  ) async {
    try {
      if(!validateform(context)){
        return;
      }
      _submitLoading = true;
      notifyListeners();
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final prov2 = Provider.of<crmLeadDetailsProvider>(context, listen: false);
      final data = await ApiCalling.crmLeadDetailsAddEditProductsAPI(
        prov.empId,
        prov.session,
        leadID,
        type,
        leadProductId,
        productId,
        addEditQuantityController.text,
        addEditProductPriceController.text,
      );
      if (data != null && data.error == "0") {
        _submitLoading = false;
        resetForm();
        Navigator.pop(context, true);
        prov2.crmLeadDetailsAPIFunction(context, leadID, mode);
        notifyListeners();
      }else{
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e, s) {
      _submitLoading = false;
      notifyListeners();
      print("Error: $e, Stack: $s");
    }
  }

  bool validateform(context){
    bool isValid = true;
    qtyError = null;
    priceError = null;
    productError = null;
    if(addEditQuantityController.text.trim().isEmpty){
      qtyError = "Please Enter Quantity";
      isValid =  false;
    }
    if(addEditTotalAmountController.text.trim().isEmpty){
      priceError = "Please Enter Price";
      isValid = false;
    }
    if (_selectedProducts == null || _selectedAddEditProductId!.isEmpty) {
      productError = "Please select a Product";
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

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

    crmLeadDetailsEditProductsSubmitAPIFunction(context, insertedData, leadID);
    submitLoading = false;
  }

  void resetForm() {
    checkDropdownReset();
    addEditProductPriceController.clear();
    addEditQuantityController.clear();
    addEditTotalAmountController.clear();
    editProductPriceControllers.clear();
    editQuantityControllers.clear();
    editTotalAmountControllers.clear();
    _selectedProductIds.clear();
    _selectedProducts = null;
    _selectedAddEditProductId = null;
    _selectedAddEditProductName = null;

    _selectedValues.clear();
    _leadProductsList.clear();
    notifyListeners();
  }

  void checkDropdownReset(){
    if(!_productsList.contains(_selectedProducts)&&_selectedProducts!=null){
      _selectedAddEditProductId = null;
      _selectedAddEditProductName = null;
    }
    notifyListeners();
  }
}
