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:get/get.dart';
import 'package:provider/provider.dart';

import '../../Models/crmModels/crmSelectedProductDetailsResponse.dart';
import 'crmProspectDetailsProvider.dart';

class Addprospectleadsprovider extends ChangeNotifier {
  TextEditingController searchController = TextEditingController();

  List<Products> _leadProductsList = [];
  List<LeadEmployees> _employeeList = [];
  List<String> _statusList = [];
  LeadEmployees? _selectedEmployees;
  String? _selectedStatus;
  String? _selectedEmployeeId;
  String? _selectedEmployeeValue;
  Products? _selectedProducts;
  String? _selectedProductsID;
  String? _selectedProductsName;
  String? _selectedProductsRemark;
  ProductsData? _selectedProductsDeatilsData;
  TextEditingController addLeadProductPriceController = TextEditingController();
  TextEditingController addLeadProductQtyController = TextEditingController();
  TextEditingController addLeadProductTotalPriceController = TextEditingController();
  TextEditingController addLeadProductRemarksController = TextEditingController();

  String? qtyError;
  String? priceError;
  String? statusError;

  List<TextEditingController> editProductPriceControllers = [];
  List<TextEditingController> editQuantityControllers = [];
  List<TextEditingController> editTotalAmountControllers = [];
  List<TextEditingController> editRemarkControllers = [];
  final List<String?> _selectedProductIds = [];
  final List<String?> _selectedValues = [];


  bool _submitLoading = false;
  ProductsData? get selectedProductsDetailsData => _selectedProductsDeatilsData;

  List<Products> get leadProductsList => _leadProductsList;

  Products? get selectedProducts => _selectedProducts;

  String? get selectedProductsID => _selectedProductsID;

  String? get selectedProductsName => _selectedProductsName;

  String? get selectedProductsRemark => _selectedProductsRemark;

  List<String?> get selectedProductIds => _selectedProductIds;

  List<String?> get selectedValues => _selectedValues;

  bool get submitLoading => _submitLoading;

  List<LeadEmployees> get employeeList => _employeeList;

  List<String> get statusList => _statusList;

  LeadEmployees? get selectedEmployee => _selectedEmployees;

  String? get selectedStatus => _selectedStatus;

  String? get selectedEmployeeId => _selectedEmployeeId;

  String? get selectedEmployeeValue => _selectedEmployeeValue;

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

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

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

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

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

  set selectedProductsID(String? value) {
    _selectedProductsID = value;
    notifyListeners();
  }

  set selectedProductsName(String? value) {
    _selectedProductsName = 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();
  }

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

  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,
          "remarks": editRemarkControllers[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,
    accountId,
    accManagerId,
    products,
    leadStatus,
  ) async {
    try {
      _submitLoading = true;
      notifyListeners();
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.crmProspectDetailsAddLeadSubmitAPI(
        prov.empId,
        prov.session,
        mode,
        accountId,
        accManagerId,
        products,
        leadStatus,
      );
      if (data != null && data.error == "0") {
        _submitLoading = false;
        resetForm();
        Navigator.pop(context, true);
        toast(context, data.message);
        notifyListeners();
      }
    } catch (e, s) {
      print("Error: $e, Stack: $s");
    }
  }

  Future<void> crmProspectDetailsAddLeadsSubmitAPIFunctionNew(
    BuildContext context,
    mode,
    leadId,
    accountId,
    productId,
    leadStatus,
  ) async {
    try {
      if (!validateform(context)) {
        return;
      }
      _submitLoading = true;
      notifyListeners();
      final prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final prov2 = Provider.of<crmProspectDetailsProvider>(
        context,
        listen: false,
      );
      final data = await ApiCalling.crmProspectDetailsAddLeadAPI(
        prov.empId,
        prov.session,
        accountId,
        productId,
        addLeadProductQtyController.text,
        addLeadProductPriceController.text,
        leadStatus,
        addLeadProductRemarksController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitLoading = false;
          resetForm();
          Navigator.pop(context, true);
          prov2.crmProspectDetailsAPIFunction(context, leadId);
          toast(context, data.message);
          notifyListeners();
        } else {
          _submitLoading = false;
          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;
    statusError = null;
    if (addLeadProductQtyController.text.trim().isEmpty) {
      qtyError = "Please Enter Quantity";
      isValid = false;
    }
    if (addLeadProductPriceController.text.trim().isEmpty) {
      priceError = "Please Enter Price";
      isValid = false;
    }
    if (_selectedStatus == null || _selectedStatus!.isEmpty) {
      statusError = "Please select a status";
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

  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;
  }

  onChnageProductPrice(value) {
    priceError = null;
    notifyListeners();
  }

  onChnageProductQty(value) {
    qtyError = null;
    notifyListeners();
  }

  onChnageProductTotalPrice(value) {
    notifyListeners();
  }

  void resetForm() {
    qtyError = null;
    priceError = null;
    statusError = null;
    searchController.clear();
    editProductPriceControllers.clear();
    addLeadProductRemarksController.clear();
    editQuantityControllers.clear();
    editTotalAmountControllers.clear();
    _selectedProductIds.clear();
    _selectedValues.clear();
    _leadProductsList.clear();
    _selectedStatus = null;
    _selectedProducts = null;
    _selectedEmployeeId = null;
    _selectedEmployeeValue = null;
    _selectedProductsID = null;
    _selectedProductsName = null;
    _selectedProductsRemark = null;
    addLeadProductPriceController.clear();
    addLeadProductQtyController.clear();
    addLeadProductTotalPriceController.clear();
    checkDropDownReset();
    notifyListeners();
  }

  checkDropDownReset() {
    // if (!_employeeList.contains(_selectedEmployees) &&
    //     _selectedEmployees != null) {
    //   _selectedEmployeeId = null;
    //   _selectedEmployeeValue = null;
    // }

    if (!_leadProductsList.contains(_selectedProducts) &&
        _selectedProducts != null) {
      _selectedProductsID = null;
      _selectedProductsName = null;
      _selectedProductsRemark = null;

    }
    notifyListeners();
  }
}
