
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/order/checkout_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_pending_screen.dart';
import 'package:cheminova/widgets/my_drawer.dart';
import 'package:cheminova/widgets/product_card.dart';
import 'package:cheminova/widgets/product_card1.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 '../../controller/cart_controller.dart';
import '../../controller/rd_processing_order_controller.dart';
import '../../models/get_rd_pennding_model.dart';
import '../../models/oder_place_model.dart';
import '../../models/product_model1.dart';
import '../../models/single_get_order_model.dart';
import '../../utils/show_snackbar.dart';
//
// class PartialProcessingDialogScreen extends StatefulWidget {
//   PlacedOrdersResponse? productModel;
//   GetRdPendingModel? productpendingModel;
//   PartialProcessingDialogScreen({super.key, this.productModel});
//
//   @override
//   State<PartialProcessingDialogScreen> createState() => _PartialProcessingDialogScreenState();
// }
//
// class _PartialProcessingDialogScreenState extends State<PartialProcessingDialogScreen> {
//   final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());
//   bool _selectAll = true; // Default to true to select all products
//   List<RDOrderItem> processingItems = [];
//   List<RDOrderItem> pendingItems = [];
//   @override
//   void initState() {
//     super.initState();
//     _separateProcessingAndPendingItems();
//   }
//   void _separateProcessingAndPendingItems() {
//     for (var item in widget.productModel!.orderItem) {
//       if (item.remainingQuantity! > 0) {
//         // If remainingQuantity > 0, it is available for processing
//         processingItems.add(item);
//       } else {
//         // If remainingQuantity == 0, it should go into pending
//         pendingItems.add(item);
//       }
//     }
//   }
//   void _showPartialOrderDialog() {
//     showDialog(
//       context: context,
//       builder: (BuildContext context) {
//         return AlertDialog(
//           title: const Text("Confirm Partial Order"),
//           content: const Text("Do you want to place a partial order for the available items?"),
//           actions: [
//             TextButton(
//               onPressed: () async {
//                 Map<String, RDOrderItem> orderItemMap = {};
//
//                 // Process only available items (processingItems)
//                 for (var item in processingItems) {
//                   var productId = item.productId;
//                   if (orderItemMap.containsKey(productId)) {
//                     var existingItem = orderItemMap[productId]!;
//                     existingItem.quantity = (existingItem.quantity ?? 0) + (item.quantity ?? 0);
//                   } else {
//                     orderItemMap[productId] = RDOrderItem(
//                       productId: productId,
//                       sku: item.sku,
//                       name: item.name,
//                       categoryName: item.categoryName,
//                       brandName: item.brandName,
//                       price: item.price,
//                       gst: item.gst,
//                       hsnCode: item.hsnCode,
//                       description: item.description,
//                       image: [],
//                       quantity: item.quantity ?? 0,
//                       remainingQuantity: item.remainingQuantity ?? 0,
//                       processquantity: item.processquantity ?? 0,
//                     );
//                   }
//                 }
//
//                 List<RDOrderItem> orderItems = orderItemMap.values.toList();
//                 controller.placedOrder1.value = PlacedOrdersProcessing(
//                   orderId: widget.productModel!.id,
//                   invoiceItems: orderItems,
//                 );
//
//                 await controller.placeRDOrder();
//                 showSnackbar("Partial order processed successfully.");
//
//                 Future.delayed(const Duration(seconds: 1), () {
//                   Navigator.of(context).pop();
//                 });
//
//                 setState(() {});
//               },
//               child: const Text("Confirm"),
//             ),
//             TextButton(
//               onPressed: () {
//                 Navigator.of(context).pop();
//               },
//               child: const Text("Cancel"),
//             ),
//           ],
//         );
//       },
//     );
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       extendBodyBehindAppBar: true,
//       appBar: AppBar(
//         backgroundColor: Colors.transparent,
//         elevation: 0,
//         leading: Builder(
//           builder: (context) {
//             return GestureDetector(
//               onTap: () => Scaffold.of(context).openDrawer(),
//               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 Center(
//           child: Text(
//             "Modify Product Availability",
//           ),
//         ),
//       ),
//       drawer: MyDrawer(),
//       body: Stack(
//         fit: StackFit.expand,
//         children: [
//           Image.asset(
//             'assets/images/image_1.png',
//             fit: BoxFit.cover,
//           ),
//           SafeArea(
//             child: Column(
//               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: [
//                         SizedBox(
//                           height: Get.height * 0.6,
//                           child: ListView.builder(
//                             padding: EdgeInsets.zero,
//                             itemCount: processingItems.length,
//                             itemBuilder: (context, index) {
//                               final orderItem = processingItems[index];
//                               return ProductCard1(productModel: orderItem);
//                             },
//                           ),
//
//                         ),
//                         const SizedBox(height: 10),
//                         Row(
//                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                           children: [
//                             Text(
//                               "Subtotal ",
//                               style: GoogleFonts.roboto(
//                                 fontSize: 15,
//                                 color: Colors.black,
//                                 fontWeight: FontWeight.bold,
//                               ),
//                             ),
//                             Text("₹ ${widget.productModel!.subtotal ?? 0}"),
//                           ],
//                         ),
//                         Row(
//                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                           children: [
//                             Text(
//                               "GST  ",
//                               style: GoogleFonts.roboto(
//                                 fontSize: 15,
//                                 color: Colors.black,
//                                 fontWeight: FontWeight.bold,
//                               ),
//                             ),
//                             Text("₹ ${widget.productModel!.gstTotal ?? 0}"),
//                           ],
//                         ),
//                         Row(
//                           mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                           children: [
//                             Text(
//                               "Total Amount ",
//                               style: GoogleFonts.roboto(
//                                 fontSize: 15,
//                                 color: Colors.black,
//                                 fontWeight: FontWeight.bold,
//                               ),
//                             ),
//                             Text("₹ ${widget.productModel!.grandTotal ?? 0}"),
//                           ],
//                         ),
//                       ],
//                     ),
//                   ),
//                 ),
//                 SizedBox(height: Get.height * 0.020),
//                 SizedBox(
//                   width: Get.width * 0.9,
//                   height: Get.height * 0.06,
//                   child: ElevatedButton(
//                     onPressed: _showPartialOrderDialog, // Show dialog when pressed
//                     style: ElevatedButton.styleFrom(
//                       foregroundColor: Colors.white,
//                       backgroundColor: const Color(0xFF00784C),
//                       shape: RoundedRectangleBorder(
//                         borderRadius: BorderRadius.circular(10),
//                       ),
//                     ),
//                     child: Text(
//                       "Submit",
//                       style: GoogleFonts.roboto(
//                         fontSize: 16,
//                         fontWeight: FontWeight.w600,
//                       ),
//                     ),
//                   ),
//                 ),
//               ],
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
//











class PartialProcessingDialogScreen extends StatefulWidget {
  final PlacedOrdersResponse? productModel;
  SingleGetOrderModel? placedOrderList;
  PartialProcessingDialogScreen({super.key, this.placedOrderList,this.productModel});

  @override
  State<PartialProcessingDialogScreen> createState() => _PartialProcessingDialogScreenState();
}

class _PartialProcessingDialogScreenState extends State<PartialProcessingDialogScreen> {
  final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());

  // Add lists for processing and pending items
  List<RDOrderItem> processingItems = [];
  List<RDOrderItem> pendingItems = [];

  @override
  void initState() {
    super.initState();
    // Separate processing and pending items based on availability
    _separateProcessingAndPendingItems();
  }

  void _separateProcessingAndPendingItems() {
    for (var item in widget.placedOrderList!.orderItem!.toList()) {
      if (item.remainingQuantity! > 0) {
        // If remainingQuantity > 0, it is available for processing
        processingItems.add(item as RDOrderItem);
      } else {
        // If remainingQuantity == 0, it should go into pending
        pendingItems.add(item as RDOrderItem);
      }
    }
  }

  void _showPartialOrderDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Confirm Partial Order"),
          content: const Text("Do you want to place a partial order for the available items?"),
          actions: [
            TextButton(
              onPressed: () async {
                Map<String, RDOrderItem> orderItemMap = {};

                // Process only available items (processingItems)
                for (var item in processingItems) {
                  var productId = item.productId;
                  if (orderItemMap.containsKey(productId)) {
                    var existingItem = orderItemMap[productId]!;
                    existingItem.quantity = (existingItem.quantity ?? 0) + (item.quantity ?? 0);
                  } else {
                    orderItemMap[productId] = RDOrderItem(
                      productId: productId,
                      sku: item.sku,
                      name: item.name,
                      categoryName: item.categoryName,
                      brandName: item.brandName,
                      price: item.price,
                      gst: item.gst,
                      hsnCode: item.hsnCode,
                      description: item.description,
                      image: [],
                      quantity: item.quantity ?? 0,
                      remainingQuantity: item.remainingQuantity ?? 0,
                      processquantity: item.processquantity ?? 0,
                    );
                  }
                }

                List<RDOrderItem> orderItems = orderItemMap.values.toList();
                controller.placedOrder1.value = PlacedOrdersProcessing(
                  orderId: widget.placedOrderList!.id,
                  invoiceItems: orderItems,
                );

                await controller.placeRDOrder();
                showSnackbar("Partial order processed successfully.");


                // Navigate to the pending screen
                Get.to(RdOrderPendingScreen());
              },
              child: const Text("Confirm"),
            ),
            TextButton(
              onPressed: () {
                //Get.back();
                Navigator.of(context).pop();
              },
              child: const Text("Cancel"),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final order = widget.placedOrderList!.orderItem[0];
    final subTotalProcesssItem = order.price! * order.remainingQuantity!.toInt();
    final GstTotalAmounProcessItem =   (order.price! * order.remainingQuantity!.toInt()) *(order.gst!/100 );
    final grandTotalProcessItem = subTotalProcesssItem + GstTotalAmounProcessItem;
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          leading: Builder(
            builder: (context) {
              return GestureDetector(
                onTap: () => Scaffold.of(context).openDrawer(),
                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 Center(
            child: Text(
              "Modify Product Availability",
            ),
          ),
        ),
        drawer: MyDrawer(),
        body: Stack(
            fit: StackFit.expand,
            children: [
              Image.asset(
                'assets/images/image_1.png',
                fit: BoxFit.cover,
              ),
              SafeArea(
                child: Column(
                  children: [
                    Expanded(
                      child: ListView(
                        children: [
                          const SizedBox(height: 20),
                          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(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    "Processing Products",
                                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                                  ),
                                  SizedBox(
                                    height: Get.height * 0.6,
                                    child: ListView.builder(
                                      itemCount: processingItems.length,
                                      itemBuilder: (context, index) {
                                        final orderItem = processingItems[index];
                                        return ProductCard1(productModel: orderItem);
                                      },
                                    ),
                                  ),
                                  const SizedBox(height: 10),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "Subtotal ",
                                        style: GoogleFonts.roboto(
                                          fontSize: 15,
                                          color: Colors.black,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text("₹ ${subTotalProcesssItem}"),
                                    ],
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "GST  ",
                                        style: GoogleFonts.roboto(
                                          fontSize: 15,
                                          color: Colors.black,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text("₹ ${widget.placedOrderList!.gstTotal ?? 0}"),
                                    ],
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "Total Amount ",
                                        style: GoogleFonts.roboto(
                                          fontSize: 15,
                                          color: Colors.black,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text("₹ ${widget.placedOrderList!.grandTotal ?? 0}"),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(height: Get.height * 0.020),
                          SizedBox(
                            width: Get.width * 0.3,
                            height: Get.height * 0.06,
                            child: ElevatedButton(
                              onPressed: _showPartialOrderDialog, // Show dialog when pressed
                              style: ElevatedButton.styleFrom(
                                foregroundColor: Colors.white,
                                backgroundColor: const Color(0xFF00784C),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                              ),
                              child: Text(
                                "Submit",
                                style: GoogleFonts.roboto(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )])
    );
  }
}

