import 'package:cheminova/screens/rd%20orders/rd_dispatched_scree.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../controller/get_dispatch_controller.dart';
import '../../controller/get_single_invoice_Service.dart';
import '../../controller/get_single_invoice_controller.dart';
import '../../controller/rd_get_order_controller.dart';
import '../../controller/rd_processing_invoice_controller.dart';
import '../../controller/rd_processing_order_controller.dart';
import '../../models/get_invoice_model.dart';
import '../../models/rd_processing_invoice_model.dart';
import '../../utils/show_snackbar.dart';
class RdOrderProcessingDetailScreen extends StatefulWidget {
 // InvoiceResponseModel? placedOrderList;
  GetInvoiceModel? placeInvoiceList;
  //final String? orderId;
  RdOrderProcessingDetailScreen({super.key ,this.placeInvoiceList,});

  @override
  State<RdOrderProcessingDetailScreen> createState() => _RdOrderProcessingDetailScreenState();
}

class _RdOrderProcessingDetailScreenState extends State<RdOrderProcessingDetailScreen> {



  final GetRDProcessingInvoiceController _getRdProductController = Get.put(GetRDProcessingInvoiceController());
  final GetSingleInvoiceController _getSingleInvoiceController = Get.put(GetSingleInvoiceController());
  final RDOrderPlacedController controller = Get.put(RDOrderPlacedController());
  final  GetDispatchController _getDispatchController = Get.put(GetDispatchController());
  final List<String> statusOptions =  [
    "new",
    "pending",
    "processing",
    "dispatched",
    "cancelled",
    "delivered",
  ];
  String selectedStatus = "processing";
  String _groupValue = "cheque";
  // Function to format date from the API to a more readable format

  List<String> _statusList = ["processing","dispatch"];
  // 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, hh:mm a').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();
  }







  // getOrder1(){
  //   _getSingleInvoiceController.fetchInvoice(widget.placeInvoiceList!.id.toString());
  //   print("dfdfdfg"'');
  // }
  void _showDispatchDetailsDialog() {
    // Only show the dialog if the selected status is "dispatch"
    if (selectedStatus != "dispatch") {
      // You can show a Snackbar or a simple AlertDialog if needed
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Dispatch option is only available when the status is "dispatch".')),
      );
      return; // Exit the function if the condition is not met
    }

    final TextEditingController _courierNameController = TextEditingController();
    final TextEditingController _courierTrackingIdController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Dispatch Details'),
          content: Column(
            mainAxisSize: MainAxisSize.min, // Shrink to fit the content
            children: [
              TextField(
                controller: _courierNameController,
                decoration: InputDecoration(
                  labelText: 'Courier Name',
                ),
              ),
              TextField(
                controller: _courierTrackingIdController,
                decoration: InputDecoration(
                  labelText: 'Courier Tracking ID',
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Close the dialog
              },
              child: Text('Cancel'),
            ),
            TextButton(
              onPressed: () {
                String courierName = _courierNameController.text;
                String courierTrackingId = _courierTrackingIdController.text;

                // Call the API to submit data
                _getDispatchController.RDProcessingToDispatchProduct(widget.placeInvoiceList!.id.toString(), courierName, courierTrackingId);
                showSnackbar("Order Status updated Order Dispatched");

                Navigator.of(context).pop(); // Close the dialog after submission
              },
              child: Text('Submit'),
            ),
          ],
        );
      },
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
   // getOrder1();
  }

  @override
  Widget build(BuildContext context) {

   // final invoiceOrder = _getSingleInvoiceController.invoice;
    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(
          "Processing Order Detail",
        ),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: SingleChildScrollView(
              child:

                // if (invoiceOrder == null) {
                //   return Center(
                //     child: Text(
                //       "No invoice data available",
                //       style: GoogleFonts.roboto(fontSize: 16),
                //     ),
                //   );
                // }
                // // Check if the items list is empty before building the UI
                // if (invoiceOrder[0]!.items == null || invoiceOrder[0]!.items!.isEmpty) {
                //   return Center(
                //     child: Text(
                //       "No items found in the invoice",
                //       style: GoogleFonts.roboto(fontSize: 16),
                //     ),
                //   );
                // }
                //final currentInvoice = invoiceOrder;
                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(
                                        "Invoices",
                                        style: GoogleFonts.roboto(
                                          fontSize: Get.width * 0.05,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                  ),

                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "Invoice ID:",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Text(widget.placeInvoiceList!.invoiceId.toString()),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            "Items: ",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          SizedBox(height: 10),
                                          Column(
                                            children: widget.placeInvoiceList!.items!.map((item) {
                                              return Padding(
                                                padding: const EdgeInsets.symmetric(vertical: 4.0),
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    Expanded(
                                                      child: Text(
                                                        "${item.name} (${item.sku})",
                                                        style: GoogleFonts.roboto(
                                                          fontSize: Get.width * 0.03,
                                                        ),
                                                        overflow: TextOverflow.ellipsis,
                                                      ),
                                                    ),
                                                    Text("x ${item.processQuantity}"),
                                                  ],
                                                ),
                                              );
                                            }).toList(),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "Sub Total: ",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Text("₹ ${widget.placeInvoiceList!.subtotal}"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "GST: ",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Text("₹ ${widget.placeInvoiceList!.gstTotal}"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "Invoice Amount: ",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Text("₹ ${widget.placeInvoiceList!.invoiceAmount}"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: Get.width,
                                    child: Padding(
                                      padding:
                                      const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment
                                            .spaceBetween,
                                        children: [
                                          Text(
                                            "Courier Status : ",
                                            style: GoogleFonts.roboto(
                                              fontSize: Get.width * 0.04,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          ElevatedButton(
                                            onPressed: () {},
                                            // Get.to(() =>
                                            //     RdOrderDetailScreen(
                                            //         placedOrderList: uniqueOrders[index])), // Navigate to detail screen
                                            style: ElevatedButton.styleFrom(
                                              foregroundColor: Colors.white,
                                              backgroundColor: Colors.orange,
                                              shape: RoundedRectangleBorder(
                                                  borderRadius: BorderRadius
                                                      .circular(10)),
                                            ),
                                            child:
                                            Text(widget.placeInvoiceList!.courierStatus.toString(),
                                                style: GoogleFonts.roboto(
                                                    fontSize: 14,
                                                    fontWeight: FontWeight
                                                        .w400)),
                                          ),
                                          //Text("₹ ${widget.placedOrderList!.gstTotal}"),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 8),

                            const SizedBox(height: 8),


                            const SizedBox(height: 8),
                            SizedBox(
                              height: Get.height* 0.19,
                              child:_buildCustomerDetails(),

                            ),
                            const SizedBox(height: 8),
                            _buildBillingInfo(),

                            const SizedBox(height: 8),
                            _buildShippingInfo(),

                            const SizedBox(height: 8),
                      _buildPaymentInfo(),
                            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(widget.placedOrderList!.status)),
                                          Text("${widget.placeInvoiceList!.courierStatus}", 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!;
                                        });
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(
                              width: Get.width * 0.4,
                              child: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: ElevatedButton(
                                  onPressed: () {
                                    //_getDispatchController.RDProcessingToDispatchProduct(widget.placedOrderList!.invoiceId, widget.placedOrderList!., couriertrackingId)
                                    _showDispatchDetailsDialog();
                                  },
                                  // 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 _buildCustomerDetails() {
    return Card(
      child: Column(
        children: [
          _buildSectionTitle("Customer Details"),
          _buildRow("Name:", widget.placeInvoiceList!.orderId!.addedBy!.name.toString(), Get.width * 0.04),
          _buildRow("Email:", widget.placeInvoiceList!.orderId!.addedBy!.email.toString(), Get.width * 0.04),
          _buildRow("Mobile Number:",  widget.placeInvoiceList!.orderId!.addedBy!.mobileNumber.toString(), Get.width * 0.04),
        ],
      ),
    );
  }

  Widget _buildBillingInfo() {
    return Card(
      child: Column(
        children: [
          _buildSectionTitle("Billing Information"),
          _buildInfoRow("Address", widget.placeInvoiceList!.orderId!.billTo.toString(), Get.width * 0.04),
        ],
      ),
    );
  }

  Widget _buildShippingInfo() {
    return Card(
      child: Column(
        children: [
          _buildSectionTitle("Shipping Information"),
          _buildInfoRow("Address", widget.placeInvoiceList!.orderId!.shipTo.toString(), Get.width * 0.04),
        ],
      ),
    );
  }

  Widget _buildPaymentInfo() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          children: [
            Text(
              "Payment Mode: ",
              style: GoogleFonts.roboto(
                fontSize: Get.width * 0.04,
                fontWeight: FontWeight.w500,
              ),
            ),
            Text(capitalizeFirstLetter(widget.placeInvoiceList!.orderId!.paymentMode.toString())),
          ],
        ),
      ),
    );
  }

}


Widget _buildSectionTitle(String title) {
  return SizedBox(
    width: Get.width,
    child: Padding(
      padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
      child: Text(
        title,
        style: GoogleFonts.roboto(fontSize: Get.width * 0.05, fontWeight: FontWeight.bold),
      ),
    ),
  );
}

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

Widget _buildInfoRow(String label, String value, double fontSize) {
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "$label: ",
          style: GoogleFonts.roboto(fontSize: fontSize, fontWeight: FontWeight.w500),
        ),
        Expanded(
          child: Text(
            value,
            style: GoogleFonts.roboto(fontSize: fontSize),
          ),
        ),
      ],
    ),
  );
}


