import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Notifiers/ordersProvider/pagesDashboardProvider.dart';
import 'package:provider/provider.dart';

import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';
import 'package:generp/Models/ordersModels/ordersDetailsDispatchOrderViewResponse.dart';

class Dispatchorderprovider extends ChangeNotifier {
  bool _submitClicked = false;
  TextEditingController invoiceNumberController = TextEditingController();
  TextEditingController vehicleNumberController = TextEditingController();
  TextEditingController driverNameController = TextEditingController();
  TextEditingController driverMobileNumberController = TextEditingController();

  String? invoiceNumberError;
  String? vehicleNumberError;
  String? driverNameError;
  String? driverMobileNumberError;

  List<Products> _leadProductsList = [];
  Products? _selectedProducts;

  List<TextEditingController> engineNumberControllers = [];
  List<TextEditingController> pdiIDControllers = [];

  final List<String?> _selectedProductIds = [];
  final List<String?> _selectedProductValues = [];

  List<Products> get productsList => _leadProductsList;
  List<Products> get leadProductsList => _leadProductsList;
  Products? get selectedProducts => _selectedProducts;
  List<String?> get selectedProductIds => _selectedProductIds;
  List<String?> get selectedProductValues => _selectedProductValues;

  bool get submitClicked => _submitClicked;

  set submitClicked(bool value) {
    _submitClicked = value;
    notifyListeners();
  }

  void initializeForm(BuildContext context) {
    // Clear existing controllers
    engineNumberControllers.clear();
    pdiIDControllers.clear();
    _selectedProductIds.clear();
    _selectedProductValues.clear();
    // Initialize controllers for each lead product
    for (var product in _leadProductsList) {
      engineNumberControllers.add(TextEditingController());
      pdiIDControllers.add(
        TextEditingController(text: product.pdiId?.toString() ?? ''),
      );

      _selectedProductIds.add(product.id);
      _selectedProductValues.add(product.productName);
    }

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

    notifyListeners();
  }

  void editAddNewRow() {
    engineNumberControllers.add(TextEditingController());
    pdiIDControllers.add(TextEditingController());
    _selectedProductIds.add(null);
    _selectedProductValues.add(null);
    notifyListeners();
  }

  void editRemoveRow(int index) {
    engineNumberControllers[index].dispose();
    pdiIDControllers[index].dispose();
    engineNumberControllers.removeAt(index);
    pdiIDControllers.removeAt(index);
    _selectedProductIds.removeAt(index);
    _selectedProductValues.removeAt(index);
    notifyListeners();
  }

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

  void updateTotalAmount(int index) {
    final price = double.tryParse(engineNumberControllers[index].text) ?? 0;
    final qty = int.tryParse(pdiIDControllers[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 < engineNumberControllers.length; i++) {
      if (_selectedProductIds[i] != null) {
        final rowData = {
          "product_id": _selectedProductIds[i]!,
          "engine_number": engineNumberControllers[i].text,
          "pdi_id": pdiIDControllers[i].text,
        };
        insertData.add(rowData);
      }
    }
    return insertData;
  }

  Future<void> ordersPDIIDByEngineNumberFunction(context, index) async {
    try {
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersPdiIdByEngNumberUrlAPI(
        provider.empId,
        provider.session,
        engineNumberControllers[index].text,
      );
      if (data != null) {
        if (data.error == "0") {
          pdiIDControllers[index].text = data.pdiId!;
          updateTotalAmount(index);
          notifyListeners();
        } else {}
      } else {}
    } catch (e) {}
  }

  Future<void> ordersDetailsDispatchOrderViewFunction(context, orderID) async {
    try {
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDetailsDispatchOrderViewAPI(
        provider.empId,
        provider.session,
        orderID,
      );
      if (data != null) {
        if (data.error == "0") {
          _leadProductsList = data.products!;
          notifyListeners();
        } else {}
      } else {}
    } catch (e) {}
  }

  Future<void> approvalRejectionAPIFunction(
    context,
    status,
    orderId,
    type,
    feedback,
    tpcApplicable,
    tpcApprovedAmount,
    saleOrderNumber,
    editCompanyName,
    crmOrderPId,
    mode,
  ) async {
    try {
      if (!validateApproveRejectForm()) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final detProvider = Provider.of<Pagesdashboardprovider>(
        context,
        listen: false,
      );
      final data = await ApiCalling.ordersDetailsApproveRejectAPI(
        provider.empId,
        provider.session,
        status,
        type,
        orderId,
        feedback,
        tpcApplicable,
        tpcApprovedAmount,
        saleOrderNumber,
        editCompanyName,
        invoiceNumberController.text,
        vehicleNumberController.text,
        driverNameController.text,
        driverMobileNumberController.text,
        crmOrderPId,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitClicked = false;
          toast(context, "${data.message}");
          resetForm();
          detProvider.ordersDetailsByModeAPIFunction(context, orderId, mode);
          Navigator.pop(context, true);
          notifyListeners();
        } else {
          _submitClicked = false;
          notifyListeners();
        }
      } else {
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  bool validateApproveRejectForm() {
    bool isValid = true;

    if (invoiceNumberController.text.trim().isEmpty) {
      invoiceNumberError = "Enter Invoice Number";
      isValid = false;
    }
    if (vehicleNumberController.text.trim().isEmpty) {
      vehicleNumberError = "Enter Vehicle Number";
      isValid = false;
    }
    if (driverNameController.text.trim().isEmpty) {
      driverNameError = "Enter Driver Name";
      isValid = false;
    }
    if (driverMobileNumberController.text.trim().isEmpty) {
      driverMobileNumberError = "Enter Driver Number";
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

  resetForm() {
    invoiceNumberController.clear();
    vehicleNumberController.clear();
    driverNameController.clear();
    driverMobileNumberController.clear();
    engineNumberControllers.clear();
    pdiIDControllers.clear();
    _selectedProductIds.clear();
    _selectedProductValues.clear();
    _leadProductsList.clear();
    invoiceNumberError = null;
    vehicleNumberError = null;
    driverNameError = null;
    driverMobileNumberError = null;
    notifyListeners();
  }

  onChangedinvoiceNumber(value) {
    invoiceNumberError = null;
    notifyListeners();
  }

  onChangedvehicleNumber(value) {
    vehicleNumberError = null;
    notifyListeners();
  }

  onChangeddriverName(value) {
    driverNameError = null;
    notifyListeners();
  }

  onChangeddriverMobileNumber(value) {
    driverMobileNumberError = null;
    notifyListeners();
  }
}
