import 'package:cheminova/controller/rd_processing_service.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/rd_order_item_model.dart';
import '../models/rd_placed_order_model.dart';
import '../utils/show_snackbar.dart';

class RDOrderPlacedController extends GetxController {
  final RDOrderPlacedService _rdOrderPlacedService = RDOrderPlacedService();

  // Observable to hold the order details
  var placedOrder1 = PlacedOrdersProcessing(
    orderId: '66ffdd0dd315eb7de3092cd6',
    invoiceItems: [
      RDOrderItem(
        productId: "66e27c190ccbf6e1c57c9fba",
        sku: "SKU045",
        name: "Testing",
        categoryName: "Testing",
        brandName: "Testing brand",
        price: 232.0,
        gst: 10,
        hsnCode: 4004,
        description: "",
        image: [],
        quantity: 1,
        remainingQuantity: 1,
        processquantity: 1,
      ),
    ],
  ).obs;

  var isLoading = false.obs;

  // Method to place an order
  Future<void> placeRDOrder() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');
    isLoading.value = true;

    try {
      // Construct the order details from the observable variable
      PlacedOrdersProcessing orderDetails = placedOrder1.value;
      print("Order Details: ${orderDetails
          .toJson()}"); // Debugging the order details

      // Call the service to place the order
      await _rdOrderPlacedService.placRDeOrder(orderDetails, token!);
    } catch (e) {
     // print("Error placing order: $e");
      showSnackbar("stock not available");
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> CancleRDProduct(String orderId, String reason) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString('token'); // Get the token

      if (token == null || token.isEmpty) {
        throw Exception("Token is missing. Please login again.");
      }

      isLoading(true); // Show loading indicator

      // Call the service function and pass the token, orderId, and reason
      await _rdOrderPlacedService.RDOrderCancel(token, orderId, reason);

      // Optionally refresh the data or show success message
      print("Order cancellation process complete.");
    } catch (e) {
      print("Error: $e");
    } finally {
      isLoading(false); // Hide loading indicator
    }
  }

}