import 'package:auto_size_text/auto_size_text.dart';
import 'package:cheminova/controller/get_order_placed_controller.dart';
import 'package:cheminova/controller/rd_get_order_controller.dart';
import 'package:cheminova/models/oder_place_model.dart';
import 'package:cheminova/models/order_item_model.dart';
import 'package:cheminova/models/place_order_list_model.dart';
import 'package:cheminova/models/rd_get_order_model.dart';
import 'package:cheminova/models/rd_order_item_model.dart';
import 'package:cheminova/models/rd_placed_order_model.dart';
import 'package:cheminova/screens/rd%20orders/partial_processing_dialog_screen.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../controller/cart_controller.dart';
import '../../controller/rd_processing_order_controller.dart';
import '../../models/product_model1.dart';
import '../../utils/show_snackbar.dart';

class RdOrderDetailScreen extends StatefulWidget {
  //final Product? productModel;
  // PlacedOrderList and PlacedOrderModel are optional parameters passed to this screen
  PlacedOrdersResponse? placedOrderList;
//  PlacedOrderModel? placedOrderModel;
  // Constructor for initializing the screen with placed order details
  RdOrderDetailScreen({super.key,this.placedOrderList});

  @override
  State<RdOrderDetailScreen> createState() =>
      _RdOrderDetailScreenState();
}


class _RdOrderDetailScreenState
    extends State<RdOrderDetailScreen> {
  // Controllers for managing cart and placed orders

  final GetProductRDController _getPlacedOrderController = Get.put(GetProductRDController());
  final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());
  String? orderId;
  final List<String> statusOptions =  [
    "new",
    "pending",
    "processing",
    "dispatched",
    "cancelled",
    "delivered",
  ];


  List<String> _statusList = ["new", "processing", "partial processing", "cancelled"]; // Default status list

  // Define different status lists for different categories
  final Map<String, List<String>> statusLists = {
    "new": ["new", "processing", "partial processing", "cancelled"],
    "pending": ["pending", "processing", "dispatched", "cancelled"],
    "dispatched": ["dispatched", "delivered", "returned", "cancelled"],
    "delivered": ["delivered", "returned", "cancelled"],
  };
  String selectedStatus = "new";
  String _groupValue = "cheque";
  // Function to format date from the API to a more readable format


  // This function updates the dropdown list dynamically based on category selection
  void updateStatusList(String category) {
    setState(() {
      _statusList = statusLists[category]!; // Update status list based on the selected category
      selectedStatus = _statusList.first; // Set the default selection to the first item
    });
  }

  String formatDate(String apiDate) {
    // Parse the API date string into a DateTime object
    DateTime parsedDate = DateTime.parse(apiDate).toLocal(); // Convert to local time

    // Format the date and time according to your specified format
    String formattedDate = DateFormat('EEE MMM dd yyyy').format(parsedDate);

    return formattedDate; // Return the formatted date string
  }

  // Function to capitalize the first letter of a string
  String capitalizeFirstLetter(String text) {
    if (text.isEmpty) return text;
    return text[0].toUpperCase() + text.substring(1).toLowerCase();
  }


  void _onPaymentModeChanged(String? value) {
    setState(() {
      _groupValue = value!;
    });
    _saveSelectedPaymentMode();
  }


  void _saveSelectedPaymentMode() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('selectedPaymentMode', _groupValue);
  }

  void _loadSelectedPaymentMode() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _groupValue = prefs.getString('selectedPaymentMode') ?? 'cheque';
    });
  }
  // Function to collect unique order IDs and corresponding order details
  Future<void> adduni()async {
    final Set<String> uniqueOrderIds = {};
    final List<PlacedOrdersResponse> uniqueOrders = [];
    // Loop through placed orders and add unique orders to the list
    for (var order in _getPlacedOrderController.productRDList) {
      if (uniqueOrderIds.add(order.uniqueId)) {
        uniqueOrders.add(order);
      }
    }
    final order = uniqueOrders[0];

    // Combine product names, categories, and quantities into strings
    final productNames = order.orderItem
        .map((item) => (item.name))
        .join(', ');
    final categotyName = order.orderItem
        .map((item) => (item.categoryName))
        .join(', ');
    final quantity =  order.orderItem
        .map((item) => (item.quantity))
        .join(', ');
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selectedStatus= widget.placedOrderList?.status ?? 'new';
    // controller.fetchOrderItems(widget.placedOrderList!.id);
  }
  void _showConfirmationDialog() {
    String dialogTitle;
    String dialogContent;
    TextEditingController reasonController = TextEditingController();

    // Set dialog title and content based on selected status
    switch (selectedStatus) {
      case "processing":
        dialogTitle = "Update Order Status";
        dialogContent = "Are you sure you want to update the status to processing?";
        break;
      case "partial processing":
        dialogTitle = "Update to Partial Processing";
        dialogContent = "Are you sure you want to update the status to 'Partial Processing'?";
        break;
      case "cancelled":
        dialogTitle = "Cancellation Reason";
        dialogContent = "Please provide a reason for cancelling the order:";
        break;
      default:
        dialogTitle = "Update Order Status";
        dialogContent = "Are you sure you want to update the status to '$selectedStatus'?";
        break;
    }

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(dialogTitle),
          content: selectedStatus == "cancelled"
              ? Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(dialogContent),
              SizedBox(height: 10),
              TextField(
                controller: reasonController,
                decoration: InputDecoration(
                  labelText: 'Cancellation Reason',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          )
              : Text(dialogContent),
          actions: [
            TextButton(
              onPressed: () async {
                if (selectedStatus == "cancelled") {
                  // Ensure the reason is provided for cancellation
                  if (reasonController.text.isEmpty) {
                    showSnackbar("Please provide a reason for cancelling the order.");
                    return; // Exit early if reason is empty
                  }

                  // Proceed with cancellation
                  await controller.CancleRDProduct(widget.placedOrderList!.id, reasonController.text);

                  // Notify user about successful cancellation
                  showSnackbar("Order cancelled successfully");

                  // Update the status in your UI or backend to reflect the cancelled state
                  setState(() {
                    // Update the status in the local model/UI
                  });

                  // Close the dialog after a short delay
                  Future.delayed(Duration(seconds: 1), () {
                    Navigator.of(context).pop(); // Close the dialog
                  });

                  return; // Exit here to prevent further processing
                }

                if (selectedStatus == "partial processing") {
                 // Get.to(() => PartialProcessingDialogScreen(productModel:  widget.placedOrderList));

                  return;
                }


                // Create a map to track products by their IDs and aggregate quantities
                Map<String, RDOrderItem> orderItemMap = {};

                // Populate the map with items and their quantities
                for (var item in _getPlacedOrderController.productRDList) {
                  var productId = item.orderItem[0].productId;

                  if (orderItemMap.containsKey(productId)) {
                    // If the product already exists, aggregate the quantity
                    var existingItem = orderItemMap[productId]!;
                    existingItem.quantity = (existingItem.quantity ?? 0) + (item.orderItem[0].quantity ?? 0);
                    existingItem.remainingQuantity = (existingItem.remainingQuantity ?? 0) + (item.orderItem[0].remainingQuantity ?? 0);
                    existingItem.processquantity = (existingItem.processquantity ?? 0) + (item.orderItem[0].processquantity ?? 0);
                  } else {
                    // If it's a new product, add it to the map
                    orderItemMap[productId] = RDOrderItem(
                      productId: productId,
                      sku: item.orderItem[0].sku,
                      name: item.orderItem[0].name,
                      categoryName: item.orderItem[0].categoryName,
                      brandName: item.orderItem[0].brandName,
                      price: item.orderItem[0].price,
                      gst: item.orderItem[0].gst.toInt(),
                      hsnCode: item.orderItem[0].hsnCode,
                      description: item.orderItem[0].description,
                      image: [], // Handle images appropriately
                      quantity: item.orderItem[0].quantity ?? 0,
                      remainingQuantity: item.orderItem[0].remainingQuantity ?? 0,
                      processquantity: item.orderItem[0].processquantity ?? 0,
                    );
                  }
                }

                // Convert the map to a list
                List<RDOrderItem> orderItems = orderItemMap.values.toList();

                // Ensure the placed order contains the correct orderId and items
                controller.placedOrder1.value = PlacedOrdersProcessing(
                  orderId: widget.placedOrderList!.id,
                  invoiceItems: orderItems,
                );

                // Debugging: Print the JSON payload
                print("Sending order payload: ${controller.placedOrder1.value.toJson()}");

                // Place the order and catch any errors
                await controller.placeRDOrder();

                showSnackbar("Order processed and invoice created successfully");
                Navigator.of(context).pop();
                // Close the dialog after a short delay

               // Close the dialog

// Refresh the UI// Refresh the UI
              },
              child: Text("Confirm"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();  // Close the dialog
              },
              child: Text("Cancel"),
            ),
          ],
        );
      },
    );
  }





  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {},
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SvgPicture.asset(
              'assets/svg/menu.svg',
            ),
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg',
              ),
            ),
          ),
        ],
        title: const Text(
          "Order Detail",
        ),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    height: Get.height * 0.02,
                  ),
                  Card(
                    margin: const EdgeInsets.symmetric(horizontal: 18),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(19),
                      side: const BorderSide(color: Color(0xFFFDFDFD)),
                    ),
                    color: const Color(0xFFB4D1E5).withOpacity(0.9),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [

                          Card(
                            child: Column(
                              children: [
                                SizedBox(
                                  width: Get.width,
                                  child: Padding(
                                    padding:
                                    const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                    child: Text(
                                      "Order Summary",
                                      style: GoogleFonts.roboto(
                                        fontSize: Get.width * 0.05,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                                _buildRow("Order ID:", widget.placedOrderList!.uniqueId, Get.width * 0.04),
                                _buildRow("Order Date:", formatDate("${widget.placedOrderList!.createdAt}"), Get.width * 0.04),
                                _buildRow("Total Items:", "${widget.placedOrderList!.orderItem.length}", Get.width * 0.04),
                                _buildRow("Sub Total:", "₹ ${widget.placedOrderList!.subtotal}", Get.width * 0.04),
                                _buildRow("GST:", "₹ ${widget.placedOrderList!.gstTotal}", Get.width * 0.04),
                                _buildRow("Total Amount:", "₹ ${widget.placedOrderList!.grandTotal}", Get.width * 0.04),


                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          Card(
                            child: SizedBox(
                              height: Get.height * 0.22,
                              child: Padding(
                                padding: EdgeInsets.all(Get.width * 0.02),
                                child: ListView.builder(
                                  padding: EdgeInsets.zero,
                                  itemCount: widget.placedOrderList?.orderItem.length ?? 0,
                                  itemBuilder: (context, index) {
                                    final orderItem = widget.placedOrderList!.orderItem[index];
                                    return orderItem != null
                                        ? Card(
                                      margin: const EdgeInsets.symmetric(vertical: 5.0),
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      child: Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Row(
                                          children: [
                                            Image.asset(
                                              "assets/images/product.png", // Add the image URL here
                                              height: 50,
                                              width: 50,
                                              fit: BoxFit.cover,
                                            ),
                                            const SizedBox(width: 10),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.end,
                                                children: [
                                                  Text(
                                                    capitalizeFirstLetter(orderItem.name),
                                                    style: GoogleFonts.roboto(
                                                      fontSize: Get.width * 0.04,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                  Text(
                                                    "Quantity: ${orderItem.quantity}",
                                                    style: GoogleFonts.roboto(
                                                      fontSize: Get.width * 0.03,
                                                    ),
                                                  ),
                                                  Text("Price: ${orderItem.price}"),
                                                  Text("Subtotal  : ${widget.placedOrderList!.subtotal}"),
                                                  Text("Gst : ${orderItem.gst}%"),
                                                  Text("GST : ${widget.placedOrderList!.gstTotal}"),
                                                  Text("Total Amount : ${widget.placedOrderList!.grandTotal}"),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    )
                                        : const SizedBox.shrink();
                                  },
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 8),
                          SizedBox(
                            height: Get.height* 0.19,
                            child: Card(
                              child: Column(
                                children: [
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding:
                                      const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Text(
                                        "Customer Details",
                                        style: GoogleFonts.roboto(
                                          fontSize: Get.width * 0.05,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                    ),
                                  ),
                                  _buildRow("Name:", " Roshan Garg", Get.width * 0.04),
                                  _buildRow("Email:", "roshangarg28@gmail.com", Get.width * 0.04),
                                  _buildRow("Mobile Number:", "8876785448", Get.width * 0.04),


                                ],
                              ),
                            ),
                          ),
                          const SizedBox(height: 8),
                          Card(
                            child: Column(
                              children: [
                                SizedBox(
                                  width: Get.width,
                                  child: Padding(
                                    padding:
                                    const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                    child: Text(
                                      "Billing Information",
                                      style: GoogleFonts.roboto(
                                        fontSize: Get.width * 0.05,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ),
                                _buildInfoRow("Address", widget.placedOrderList!.billTo,  Get.width * 0.04)

                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          // Card for displaying shipping information
                          Card(
                            child: Column(
                              children: [
                                SizedBox(
                                  width: Get.width,
                                  child: Padding(
                                    padding:
                                    const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                    child: Text(
                                      "Shipping Information",
                                      style: GoogleFonts.roboto(
                                        fontSize: Get.width * 0.05,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ),
                                _buildInfoRow("Address", widget.placedOrderList!.shipTo,  Get.width * 0.04)


                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          Card(
                            child: Column(
                              children: [
                                SizedBox(
                                  width: Get.width,
                                  height: Get.height*0.05,
                                  child: Padding(
                                    padding:
                                    const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                    child: Row(
                                      children: [
                                        Text(
                                          "Payment Mode : ",
                                          style: GoogleFonts.roboto(
                                            fontSize: Get.width * 0.04,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                        Text(capitalizeFirstLetter(widget.placedOrderList!.paymentMode)),
                                        // Text("${widget.placedOrderList!.paymentMode}",maxLines: 4,
                                        //   overflow:TextOverflow.ellipsis,)
                                      ],
                                    ),
                                  ),
                                ),


                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          Card(
                            child: Column(
                              children: [
                                SizedBox(
                                  width: Get.width,
                                  height: Get.height*0.05,
                                  child: Padding(
                                    padding:
                                    const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                    child: Row(
                                      children: [
                                        Text(
                                          "Order Status :",
                                          style: GoogleFonts.roboto(
                                            fontSize: Get.width * 0.04,
                                            fontWeight: FontWeight.w500,
                                          ),
                                        ),
                                        SizedBox(width: Get.width*0.01,),
                                        Text(capitalizeFirstLetter(selectedStatus)),
                                        // Text("${widget.placedOrderList!.status}",maxLines: 4,
                                        //   overflow:TextOverflow.ellipsis,)
                                      ],
                                    ),
                                  ),
                                ),


                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          SizedBox(
                            height: Get.height * 0.05,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const Text(
                                  "Status: ",
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                ),
                                SizedBox(width: 10), // Space between label and dropdown
                                Expanded(
                                  child: DropdownButtonFormField<String>(
                                    value: selectedStatus,
                                    decoration: InputDecoration(
                                      filled: true,
                                      fillColor: Colors.white, // White background
                                      contentPadding: EdgeInsets.symmetric(
                                          vertical: 10, horizontal: 12),
                                      border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(10),
                                        borderSide: BorderSide(
                                          color: Colors.grey,
                                          width: 1,
                                        ),
                                      ),
                                    ),
                                    items: _statusList.map((String status) {
                                      return DropdownMenuItem<String>(
                                        value: status,
                                        child: Text(capitalizeFirstLetter(status)),
                                      );
                                    }).toList(),
                                    onChanged: (newValue) {
                                      setState(() {
                                        selectedStatus = newValue!;
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                          if (selectedStatus == "processing" ||
                              selectedStatus == "partial processing" ||
                              selectedStatus == "cancelled")
                            SizedBox(
                              width: Get.width * 0.4,
                              child: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: ElevatedButton(
                                  onPressed: () {
                                    // Show confirmation dialog
                                    _showConfirmationDialog();
                                  },
                                  // Get.to(() =>
                                  //     RdOrderDetailScreen(
                                  //         placedOrderList: uniqueOrders[index])), // Navigate to detail screen
                                  style: ElevatedButton.styleFrom(
                                    foregroundColor: Colors.white,
                                    backgroundColor: const Color(0xFF004791),
                                    shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(10)),
                                  ),
                                  child: Text("Update Status", style: GoogleFonts.roboto(fontSize: 14, fontWeight: FontWeight.w400)),
                                ),
                              ),
                            )

                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: Get.height * 0.04),

                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
Widget _buildRow(String label, String value, double fontSize) {
  return SizedBox(
    width: Get.width,
    child: Padding(
      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: GoogleFonts.roboto(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(value),
        ],
      ),
    ),
  );
}

Widget _buildInfoRow(String label, String value, double fontSize) {
  return SizedBox(
    width: Get.width,
    child: Padding(
      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
      child: Row(
        children: [
          Text(
            "$label ",
            style: GoogleFonts.roboto(
              fontSize: fontSize,
              fontWeight: FontWeight.bold,
            ),
          ),
          Expanded(
            child: Text(
              value,
              maxLines: 4,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    ),
  );

}





// import 'package:auto_size_text/auto_size_text.dart';
// import 'package:cheminova/controller/get_order_placed_controller.dart';
// import 'package:cheminova/controller/rd_get_order_controller.dart';
// import 'package:cheminova/models/oder_place_model.dart';
// import 'package:cheminova/models/order_item_model.dart';
// import 'package:cheminova/models/place_order_list_model.dart';
// import 'package:cheminova/models/rd_get_order_model.dart';
// import 'package:cheminova/models/rd_order_item_model.dart';
// import 'package:cheminova/models/rd_placed_order_model.dart';
// import 'package:cheminova/screens/rd%20orders/partial_processing_dialog_screen.dart';
//
// import 'package:flutter/cupertino.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter_svg/svg.dart';
// import 'package:get/get.dart';
// import 'package:google_fonts/google_fonts.dart';
// import 'package:intl/intl.dart';
// import 'package:shared_preferences/shared_preferences.dart';
//
// import '../../controller/cart_controller.dart';
// import '../../controller/rd_processing_order_controller.dart';
// import '../../models/product_model1.dart';
// import '../../utils/show_snackbar.dart';
//
// class RdOrderDetailScreen extends StatefulWidget {
//   //final Product? productModel;
//   // PlacedOrderList and PlacedOrderModel are optional parameters passed to this screen
//   PlacedOrdersResponse? placedOrderList;
// //  PlacedOrderModel? placedOrderModel;
//   // Constructor for initializing the screen with placed order details
//   RdOrderDetailScreen({super.key,this.placedOrderList});
//
//   @override
//   State<RdOrderDetailScreen> createState() =>
//       _RdOrderDetailScreenState();
// }
//
//
// class _RdOrderDetailScreenState
//     extends State<RdOrderDetailScreen> {
//   // Controllers for managing cart and placed orders
//
//   final GetProductRDController _getPlacedOrderController = Get.put(GetProductRDController());
//   final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());
//   String? orderId;
//   final List<String> statusOptions =  [
//     "new",
//     "pending",
//     "processing",
//     "dispatched",
//     "cancelled",
//     "delivered",
//   ];
//
//
//   List<String> _statusList = ["new", "processing", "partial processing", "cancelled"]; // Default status list
//
//   // Define different status lists for different categories
//   final Map<String, List<String>> statusLists = {
//     "new": ["new", "processing", "partial processing", "cancelled"],
//     "pending": ["pending", "processing", "dispatched", "cancelled"],
//     "dispatched": ["dispatched", "delivered", "returned", "cancelled"],
//     "delivered": ["delivered", "returned", "cancelled"],
//   };
//   String selectedStatus = "new";
//   String _groupValue = "cheque";
//   // Function to format date from the API to a more readable format
//
//
//   // This function updates the dropdown list dynamically based on category selection
//   void updateStatusList(String category) {
//     setState(() {
//       _statusList = statusLists[category]!; // Update status list based on the selected category
//       selectedStatus = _statusList.first; // Set the default selection to the first item
//     });
//   }
//
//   String formatDate(String apiDate) {
//
//     DateTime parsedDate = DateTime.parse(apiDate);
//
//     String formattedDate = DateFormat('dd-MMM-yyyy').format(parsedDate);
//
//     return formattedDate;
//   }
//   // Function to capitalize the first letter of a string
//   String capitalizeFirstLetter(String text) {
//     if (text.isEmpty) return text;
//     return text[0].toUpperCase() + text.substring(1).toLowerCase();
//   }
//
//
//   void _onPaymentModeChanged(String? value) {
//     setState(() {
//       _groupValue = value!;
//     });
//     _saveSelectedPaymentMode();
//   }
//
//
//   void _saveSelectedPaymentMode() async {
//     SharedPreferences prefs = await SharedPreferences.getInstance();
//     await prefs.setString('selectedPaymentMode', _groupValue);
//   }
//
//   void _loadSelectedPaymentMode() async {
//     SharedPreferences prefs = await SharedPreferences.getInstance();
//     setState(() {
//       _groupValue = prefs.getString('selectedPaymentMode') ?? 'cheque';
//     });
//   }
//   // Function to collect unique order IDs and corresponding order details
//   Future<void> adduni()async {
//     final Set<String> uniqueOrderIds = {};
//     final List<PlacedOrdersResponse> uniqueOrders = [];
//     // Loop through placed orders and add unique orders to the list
//     for (var order in _getPlacedOrderController.productRDList) {
//       if (uniqueOrderIds.add(order.uniqueId)) {
//         uniqueOrders.add(order);
//       }
//     }
//     final order = uniqueOrders[0];
//
//     // Combine product names, categories, and quantities into strings
//     final productNames = order.orderItem
//         .map((item) => (item.name))
//         .join(', ');
//     final categotyName = order.orderItem
//         .map((item) => (item.categoryName))
//         .join(', ');
//     final quantity =  order.orderItem
//         .map((item) => (item.quantity))
//         .join(', ');
//   }
//   @override
//   void initState() {
//     // TODO: implement initState
//     super.initState();
//     selectedStatus= widget.placedOrderList?.status ?? 'new';
//     // controller.fetchOrderItems(widget.placedOrderList!.id);
//   }
//
//   void _showConfirmationDialog() {
//     String dialogTitle;
//     String dialogContent;
//     TextEditingController reasonController = TextEditingController();
//
//     // Set dialog title and content based on selected status
//     switch (selectedStatus) {
//       case "processing":
//         dialogTitle = "Update Order Status";
//         dialogContent = "Are you sure you want to update the status to processing?";
//         break;
//       case "partial processing":
//         dialogTitle = "Update to Partial Processing";
//         dialogContent = "Are you sure you want to update the status to 'Partial Processing'?";
//         break;
//       case "cancelled":
//         dialogTitle = "Cancellation Reason";
//         dialogContent = "Please provide a reason for cancelling the order:";
//         break;
//       default:
//         dialogTitle = "Update Order Status";
//         dialogContent = "Are you sure you want to update the status to '$selectedStatus'?";
//         break;
//     }
//
//     showDialog(
//       context: context,
//       builder: (context) {
//         return AlertDialog(
//           title: Text(dialogTitle),
//           content: selectedStatus == "cancelled"
//               ? Column(
//             mainAxisSize: MainAxisSize.min,
//             children: [
//               Text(dialogContent),
//               SizedBox(height: 10),
//               TextField(
//                 controller: reasonController,
//                 decoration: InputDecoration(
//                   labelText: 'Cancellation Reason',
//                   border: OutlineInputBorder(),
//                 ),
//               ),
//             ],
//           )
//               : Text(dialogContent),
//           actions: [
//             TextButton(
//               onPressed: () async {
//                 if (selectedStatus == "cancelled") {
//                   // Ensure the reason is provided for cancellation
//                   if (reasonController.text.isEmpty) {
//                     showSnackbar("Please provide a reason for cancelling the order.");
//                     return; // Exit early if reason is empty
//                   }
//
//                   // Proceed with cancellation
//                   await controller.CancleRDProduct(widget.placedOrderList!.id, reasonController.text);
//
//                   // Notify user about successful cancellation
//                   showSnackbar("Order cancelled successfully");
//
//                   // Update the status in your UI or backend to reflect the cancelled state
//                   setState(() {
//                     // Update the status in the local model/UI
//                   });
//
//                   // Close the dialog after a short delay
//                   Future.delayed(Duration(seconds: 1), () {
//                     Get.back(); // Close the dialog
//                   });
//
//                   return; // Exit here to prevent further processing
//                 }
//
//                 if (selectedStatus == "partial processing") {
//                   Get.to(() => PartialProcessingDialogScreen(productModel:  widget.placedOrderList));
//                   return;
//                 }
//
//                 // Create a map to track products by their IDs and aggregate quantities
//                 Map<String, RDOrderItem> orderItemMap = {};
//
//                 // Populate the map with items and their quantities
//                 for (var item in _getPlacedOrderController.productRDList) {
//                   var productId = item.orderItem[0].productId;
//
//                   if (orderItemMap.containsKey(productId)) {
//                     // If the product already exists, aggregate the quantity
//                     var existingItem = orderItemMap[productId]!; // Get the existing item
//                     existingItem.quantity = (existingItem.quantity ?? 0) + (item.orderItem[0].quantity ?? 0);
//                   } else {
//                     // If it's a new product, add it to the map
//                     orderItemMap[productId] = RDOrderItem(
//                       productId: productId,
//                       sku: item.orderItem[0].sku,
//                       name: item.orderItem[0].name,
//                       categoryName: item.orderItem[0].categoryName,
//                       brandName: item.orderItem[0].brandName,
//                       price: item.orderItem[0].price,
//                       gst: item.orderItem[0].gst,
//                       hsnCode: item.orderItem[0].hsnCode,
//                       description: item.orderItem[0].description,
//                       image: [], // Handle images appropriately
//                       quantity: item.orderItem[0].quantity??0,
//                       remainingQuantity: item.orderItem[0].remainingQuantity??0,
//                       processquantity: item.orderItem[0].processquantity??0,
//                     );
//                   }
//                 }
//
//                 // Convert the map to a list
//                 List<RDOrderItem> orderItems = orderItemMap.values.toList();
//
//                 // Ensure the placed order contains the correct orderId and items
//                 controller.placedOrder1.value = PlacedOrdersProcessing(
//                   orderId: widget.placedOrderList!.id,
//                   invoiceItems: orderItems,
//                 );
//
//                 // Debugging: Print the JSON payload
//                 print(controller.placedOrder1.value.toJson());
//
//                 await controller.placeRDOrder();
//
//                 showSnackbar("Order processed and invoice created successfully");
//
//                 Future.delayed(Duration(seconds: 1), () {
//                   Get.back(); // Close the dialog
//                 });
//
//                 setState(() {}); // Refresh the UI
//               },
//               child: Text("Confirm"),
//             ),
//             TextButton(
//               onPressed: () {
//                 Get.back(); // Close the dialog
//               },
//               child: Text("Cancel"),
//             ),
//           ],
//         );
//       },
//     );
//   }
//
//
//
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       extendBodyBehindAppBar: true,
//       appBar: AppBar(
//         backgroundColor: Colors.transparent,
//         elevation: 0,
//         leading: GestureDetector(
//           onTap: () {},
//           child: Padding(
//             padding: const EdgeInsets.all(16.0),
//             child: SvgPicture.asset(
//               'assets/svg/menu.svg',
//             ),
//           ),
//         ),
//         actions: [
//           GestureDetector(
//             onTap: () => Get.back(),
//             child: Padding(
//               padding: const EdgeInsets.all(8.0),
//               child: SvgPicture.asset(
//                 'assets/svg/back_arrow.svg',
//               ),
//             ),
//           ),
//         ],
//         title: const Text(
//           "Order Detail",
//         ),
//       ),
//       body: Stack(
//         fit: StackFit.expand,
//         children: [
//           Image.asset(
//             'assets/images/image_1.png',
//             fit: BoxFit.cover,
//           ),
//           SafeArea(
//             child: SingleChildScrollView(
//               child: Column(
//                 mainAxisSize: MainAxisSize.min,
//                 mainAxisAlignment: MainAxisAlignment.start,
//                 children: [
//                   SizedBox(
//                     height: Get.height * 0.02,
//                   ),
//                   Card(
//                     margin: const EdgeInsets.symmetric(horizontal: 18),
//                     shape: RoundedRectangleBorder(
//                       borderRadius: BorderRadius.circular(19),
//                       side: const BorderSide(color: Color(0xFFFDFDFD)),
//                     ),
//                     color: const Color(0xFFB4D1E5).withOpacity(0.9),
//                     child: Padding(
//                       padding: const EdgeInsets.all(12.0),
//                       child: Column(
//                         mainAxisSize: MainAxisSize.min,
//                         children: [
//
//                           Card(
//                             child: Column(
//                               children: [
//                                 SizedBox(
//                                   width: Get.width,
//                                   child: Padding(
//                                     padding:
//                                     const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                     child: Text(
//                                       "Order Summary",
//                                       style: GoogleFonts.roboto(
//                                         fontSize: Get.width * 0.05,
//                                         fontWeight: FontWeight.bold,
//                                       ),
//                                     ),
//                                   ),
//                                 ),
//                                 _buildRow("Order ID:", widget.placedOrderList!.uniqueId, Get.width * 0.04),
//                                 _buildRow("Order Date:", formatDate("${widget.placedOrderList!.createdAt}"), Get.width * 0.04),
//                                 _buildRow("Total Items:", "${widget.placedOrderList!.orderItem.length}", Get.width * 0.04),
//                                 _buildRow("Sub Total:", "₹ ${widget.placedOrderList!.subtotal}", Get.width * 0.04),
//                                 _buildRow("GST:", "₹ ${widget.placedOrderList!.gstTotal}", Get.width * 0.04),
//                                 _buildRow("Total Amount:", "₹ ${widget.placedOrderList!.grandTotal}", Get.width * 0.04),
//
//
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           Card(
//                             child: SizedBox(
//                               height: Get.height * 0.22,
//                               child: Padding(
//                                 padding: EdgeInsets.all(Get.width * 0.02),
//                                 child: ListView.builder(
//                                   padding: EdgeInsets.zero,
//                                   itemCount: widget.placedOrderList?.orderItem.length ?? 0,
//                                   itemBuilder: (context, index) {
//                                     final orderItem = widget.placedOrderList!.orderItem[index];
//                                     return orderItem != null
//                                         ? Card(
//                                       margin: const EdgeInsets.symmetric(vertical: 5.0),
//                                       shape: RoundedRectangleBorder(
//                                         borderRadius: BorderRadius.circular(10),
//                                       ),
//                                       child: Padding(
//                                         padding: const EdgeInsets.all(8.0),
//                                         child: Row(
//                                           children: [
//                                             Image.asset(
//                                               "assets/images/product.png", // Add the image URL here
//                                               height: 50,
//                                               width: 50,
//                                               fit: BoxFit.cover,
//                                             ),
//                                             const SizedBox(width: 10),
//                                             Expanded(
//                                               child: Column(
//                                                 crossAxisAlignment: CrossAxisAlignment.end,
//                                                 children: [
//                                                   Text(
//                                                     capitalizeFirstLetter(orderItem.name),
//                                                     style: GoogleFonts.roboto(
//                                                       fontSize: Get.width * 0.04,
//                                                       fontWeight: FontWeight.bold,
//                                                     ),
//                                                   ),
//                                                   Text(
//                                                     "Quantity: ${orderItem.quantity}",
//                                                     style: GoogleFonts.roboto(
//                                                       fontSize: Get.width * 0.03,
//                                                     ),
//                                                   ),
//                                                   Text("Price: ${orderItem.price}"),
//                                                   Text("Subtotal  : ${widget.placedOrderList!.subtotal}"),
//                                                   Text("Gst : ${orderItem.gst}%"),
//                                                   Text("GST : ${widget.placedOrderList!.gstTotal}"),
//                                                   Text("Total Amount : ${widget.placedOrderList!.grandTotal}"),
//                                                 ],
//                                               ),
//                                             ),
//                                           ],
//                                         ),
//                                       ),
//                                     )
//                                         : const SizedBox.shrink();
//                                   },
//                                 ),
//                               ),
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           SizedBox(
//                             height: Get.height* 0.19,
//                             child: Card(
//                               child: Column(
//                                 children: [
//                                   SizedBox(
//                                     width: Get.width,
//                                     child: Padding(
//                                       padding:
//                                       const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                       child: Text(
//                                         "Customer Details",
//                                         style: GoogleFonts.roboto(
//                                           fontSize: Get.width * 0.05,
//                                           fontWeight: FontWeight.w500,
//                                         ),
//                                       ),
//                                     ),
//                                   ),
//                                   _buildRow("Name:", "VAIBHAV", Get.width * 0.04),
//                                   _buildRow("Email:", "vaibhav.gurjar20001@gmail.com", Get.width * 0.04),
//                                   _buildRow("Mobile Number:", "7779797976", Get.width * 0.04),
//
//
//                                 ],
//                               ),
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           Card(
//                             child: Column(
//                               children: [
//                                 SizedBox(
//                                   width: Get.width,
//                                   child: Padding(
//                                     padding:
//                                     const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                     child: Text(
//                                       "Billing Information",
//                                       style: GoogleFonts.roboto(
//                                         fontSize: Get.width * 0.05,
//                                         fontWeight: FontWeight.w500,
//                                       ),
//                                     ),
//                                   ),
//                                 ),
//                                 _buildInfoRow("Address", widget.placedOrderList!.billTo,  Get.width * 0.04)
//
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           // Card for displaying shipping information
//                           Card(
//                             child: Column(
//                               children: [
//                                 SizedBox(
//                                   width: Get.width,
//                                   child: Padding(
//                                     padding:
//                                     const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                     child: Text(
//                                       "Shipping Information",
//                                       style: GoogleFonts.roboto(
//                                         fontSize: Get.width * 0.05,
//                                         fontWeight: FontWeight.w500,
//                                       ),
//                                     ),
//                                   ),
//                                 ),
//                                 _buildInfoRow("Address", widget.placedOrderList!.shipTo,  Get.width * 0.04)
//
//
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           Card(
//                             child: Column(
//                               children: [
//                                 SizedBox(
//                                   width: Get.width,
//                                   height: Get.height*0.05,
//                                   child: Padding(
//                                     padding:
//                                     const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                     child: Row(
//                                       children: [
//                                         Text(
//                                           "Payment Mode : ",
//                                           style: GoogleFonts.roboto(
//                                             fontSize: Get.width * 0.04,
//                                             fontWeight: FontWeight.w500,
//                                           ),
//                                         ),
//                                         Text(capitalizeFirstLetter(widget.placedOrderList!.paymentMode)),
//                                         // Text("${widget.placedOrderList!.paymentMode}",maxLines: 4,
//                                         //   overflow:TextOverflow.ellipsis,)
//                                       ],
//                                     ),
//                                   ),
//                                 ),
//
//
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           Card(
//                             child: Column(
//                               children: [
//                                 SizedBox(
//                                   width: Get.width,
//                                   height: Get.height*0.05,
//                                   child: Padding(
//                                     padding:
//                                     const EdgeInsets.fromLTRB(8, 8, 8, 0),
//                                     child: Row(
//                                       children: [
//                                         Text(
//                                           "Order Status :",
//                                           style: GoogleFonts.roboto(
//                                             fontSize: Get.width * 0.04,
//                                             fontWeight: FontWeight.w500,
//                                           ),
//                                         ),
//                                         SizedBox(width: Get.width*0.01,),
//                                         Text(capitalizeFirstLetter(selectedStatus)),
//                                         // Text("${widget.placedOrderList!.status}",maxLines: 4,
//                                         //   overflow:TextOverflow.ellipsis,)
//                                       ],
//                                     ),
//                                   ),
//                                 ),
//
//
//                               ],
//                             ),
//                           ),
//                           const SizedBox(height: 8),
//                           SizedBox(
//                             height: Get.height * 0.05,
//                             child: Row(
//                               crossAxisAlignment: CrossAxisAlignment.center,
//                               children: [
//                                 const Text(
//                                   "Status: ",
//                                   style: TextStyle(fontWeight: FontWeight.bold),
//                                 ),
//                                 SizedBox(width: 10), // Space between label and dropdown
//                                 Expanded(
//                                   child: DropdownButtonFormField<String>(
//                                     value: selectedStatus,
//                                     decoration: InputDecoration(
//                                       filled: true,
//                                       fillColor: Colors.white, // White background
//                                       contentPadding: EdgeInsets.symmetric(
//                                           vertical: 10, horizontal: 12),
//                                       border: OutlineInputBorder(
//                                         borderRadius: BorderRadius.circular(10),
//                                         borderSide: BorderSide(
//                                           color: Colors.grey,
//                                           width: 1,
//                                         ),
//                                       ),
//                                     ),
//                                     items: _statusList.map((String status) {
//                                       return DropdownMenuItem<String>(
//                                         value: status,
//                                         child: Text(capitalizeFirstLetter(status)),
//                                       );
//                                     }).toList(),
//                                     onChanged: (newValue) {
//                                       setState(() {
//                                         selectedStatus = newValue!;
//                                       });
//                                     },
//                                   ),
//                                 ),
//                               ],
//                             ),
//                           ),
//                           if (selectedStatus == "processing" ||
//                               selectedStatus == "partial processing" ||
//                               selectedStatus == "cancelled")
//                             SizedBox(
//                               width: Get.width * 0.4,
//                               child: Padding(
//                                 padding: const EdgeInsets.all(8.0),
//                                 child: ElevatedButton(
//                                   onPressed: () {
//                                     // Show confirmation dialog
//                                     _showConfirmationDialog();
//                                   },
//                                   // Get.to(() =>
//                                   //     RdOrderDetailScreen(
//                                   //         placedOrderList: uniqueOrders[index])), // Navigate to detail screen
//                                   style: ElevatedButton.styleFrom(
//                                     foregroundColor: Colors.white,
//                                     backgroundColor: const Color(0xFF004791),
//                                     shape: RoundedRectangleBorder(
//                                         borderRadius: BorderRadius.circular(10)),
//                                   ),
//                                   child: Text("Update Status", style: GoogleFonts.roboto(fontSize: 14, fontWeight: FontWeight.w400)),
//                                 ),
//                               ),
//                             )
//
//                         ],
//                       ),
//                     ),
//                   ),
//                   SizedBox(height: Get.height * 0.04),
//
//                 ],
//               ),
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
// Widget _buildRow(String label, String value, double fontSize) {
//   return SizedBox(
//     width: Get.width,
//     child: Padding(
//       padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
//       child: Row(
//         mainAxisAlignment: MainAxisAlignment.spaceBetween,
//         children: [
//           Text(
//             label,
//             style: GoogleFonts.roboto(
//               fontSize: fontSize,
//               fontWeight: FontWeight.bold,
//             ),
//           ),
//           Text(value),
//         ],
//       ),
//     ),
//   );
// }
//
// Widget _buildInfoRow(String label, String value, double fontSize) {
//   return SizedBox(
//     width: Get.width,
//     child: Padding(
//       padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
//       child: Row(
//         children: [
//           Text(
//             "$label ",
//             style: GoogleFonts.roboto(
//               fontSize: fontSize,
//               fontWeight: FontWeight.bold,
//             ),
//           ),
//           Expanded(
//             child: Text(
//               value,
//               maxLines: 4,
//               overflow: TextOverflow.ellipsis,
//             ),
//           ),
//         ],
//       ),
//     ),
//   );
//
// }
//
//
//
//
//
