import 'package:cheminova/controller/rd_get_order_controller.dart';
import 'package:cheminova/models/rd_get_order_model.dart';
import 'package:cheminova/screens/rd%20orders/rd_cancelled_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_delivered_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_dispatched_scree.dart';
import 'package:cheminova/screens/rd%20orders/rd_order_details_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_order_details_update.dart';
import 'package:cheminova/screens/rd%20orders/rd_pending_screen.dart';
import 'package:cheminova/screens/rd%20orders/rd_processing_screen.dart';
import 'package:cheminova/widgets/input_field.dart';
import 'package:cheminova/widgets/my_drawer.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/rd_get_single_service.dart';
import '../../controller/rd_single_order_controller.dart';
import '../../models/single_get_order_model.dart';
import '../order_management/order_management_detail_screen.dart';

class RdOrderScreen extends StatefulWidget {
  final PlacedOrdersResponse? getrdProduct;
  SingleGetOrderModel? getSingleProduct;

  RdOrderScreen({super.key, this.getrdProduct, this.getSingleProduct});

  @override
  State<RdOrderScreen> createState() => _RdOrderScreenState();
}

class _RdOrderScreenState extends State<RdOrderScreen> {
  final _searchController = TextEditingController();
  final List<String> _filterList = [
    "new",
    "pending",
    "processing",
    "dispatched",
    "cancelled",
    "delivered",
  ];
  int _selectedIndex = 0;
  final GetProductRDController _getRdProductController =
      Get.put(GetProductRDController());
  final RdSingleOrderController _getrdSingleOrderController =
      Get.put(RdSingleOrderController());
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    getOrder1();
    getOrder3();
    //  getOrder3(_getrdSingleOrderController.productRDOrderSingleList[0].id);
  }

  Future<void> _onRefresh() async {
    await getOrder1();

    await Future.delayed(Duration(seconds: 1));
  }

  Future<void> getOrder1() async {
    await _getRdProductController.fetchRDProduct();
    if (_getRdProductController.productRDList.isEmpty) {
      print("No orders found.");
    } else {
      print(" New Orders fetched successfully");
    }
  }

  Future<void> getOrder3() async {
    //_getrdSingleOrderController.fetchAllOrdersAndSingleOrder();
  }

  String capitalizeFirstLetter(String text) {
    if (text.isEmpty) return text;
    return text[0].toUpperCase() + text.substring(1).toLowerCase();
  }

  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
  }




  // void onOrderTap(int index) async {
  //   // Fetch orders and ensure you wait for it to complete
  //   await _getrdSingleOrderController.fetchAllOrdersAndSingleOrder();
  //
  //   // Log the length of the list to help with debugging
  //   print('Fetched orders count: ${_getrdSingleOrderController.productRDOrderSingleList.length}');
  //
  //   // Check if the productRDOrderSingleList is not empty
  //   if (_getrdSingleOrderController.productRDOrderSingleList.isNotEmpty) {
  //     // Ensure the index is within range
  //     if (index >= 0 && index < _getrdSingleOrderController.productRDOrderSingleList.length) {
  //       // Get the order ID from the list based on the index
  //       final orderId = _getrdSingleOrderController.productRDOrderSingleList[index].id;
  //
  //       // Retrieve the token from SharedPreferences
  //       SharedPreferences prefs = await SharedPreferences.getInstance();
  //       String? token = prefs.getString('token');
  //
  //       // Fetch the single order using the order ID
  //       final singleOrder = await GetSingleProductService().getSingleOrder(token!, orderId);
  //
  //       // Check if the single order was fetched successfully
  //       if (singleOrder != null) {
  //         // Navigate to the details screen with the fetched order
  //         Get.to(() => RdOrderDetailUpdateScreen(placedOrderList: singleOrder, orderId: orderId,));
  //       } else {
  //         // Handle the case where the single order could not be fetched
  //         Get.snackbar("Error", "Unable to fetch order details.");
  //       }
  //     } else {
  //       // Handle the case when the index is out of bounds
  //       Get.snackbar("Error", "Invalid order selection.");
  //     }
  //   } else {
  //     // Handle the case when the list is empty
  //     Get.snackbar("Error", "No orders available to display.");
  //   }
  // }


  void onOrderTap(int index) async {
    try {
      // Fetch orders and ensure you wait for it to complete
      await _getRdProductController.fetchRDProduct();

      // Log the count of fetched orders
      print('Fetched orders count: ${_getRdProductController.productRDList.length}');

      // Check if the productRDList is populated
      if (_getRdProductController.productRDList.isNotEmpty) {
        // Ensure the index is valid
        if (index >= 0 && index < _getRdProductController.productRDList.length) {
          // Get the order ID from the list based on the index
          final orderId = _getRdProductController.productRDList[index].id;

          // Retrieve the token from SharedPreferences
          SharedPreferences prefs = await SharedPreferences.getInstance();
          String? token = prefs.getString('token');

          // Check if the token is not null
          if (token != null) {
            // Fetch the single order using the order ID, and avoid caching issues
            final singleOrder = await GetSingleProductService().getSingleOrder(token, orderId);

            // Check if the single order was fetched successfully
            if (singleOrder != null) {
              // Navigate to the details screen with the fetched order
              Get.to(() => RdOrderDetailUpdateScreen(
                placedOrderList: singleOrder,
                orderId: orderId,
              ));
            } else {
              // Handle the case where the single order could not be fetched
              Get.snackbar("Error", "Unable to fetch order details.");
            }
          } else {
            // Handle the case where the token is null
            Get.snackbar("Error", "User not authenticated.");
          }
        } else {
          // Handle the case when the index is out of bounds
          Get.snackbar("Error", "Invalid order selection.");
        }
      } else {
        // Handle the case when the list is empty
        Get.snackbar("Error", "No orders available to display.");
      }
    } catch (e) {
      // Log any errors that occur during the process
      print('Error in onOrderTap: $e');
      Get.snackbar("Error", "An unexpected error occurred.");
    }
  }







  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        centerTitle: true,
        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 Text("RD Order"),
      ),
      drawer: MyDrawer(),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset('assets/images/image_1.png', fit: BoxFit.cover),
          SafeArea(
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom),
                child: RefreshIndicator(
                  key: _refreshIndicatorKey,
                  onRefresh: _onRefresh,
                  color: Colors.black,
                  backgroundColor: Colors.white,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      InputField(
                        hintText: "Search Order",
                        labelText: "Search Order",
                        controller: _searchController,
                      ),
                      SizedBox(height: Get.height * 0.035),
                      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.05,
                                child: ListView.builder(
                                  shrinkWrap: true,
                                  scrollDirection: Axis.horizontal,
                                  itemCount: _filterList.length,
                                  itemBuilder: (context, index) => Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 4),
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          _selectedIndex =
                                              index; // Update selected index
                                        });
                                        // Navigate to different screens based on selected tab
                                        switch (_filterList[index]) {
                                          case "new":
                                            //  Get.to(YourScreen1()); // Navigate to "new" orders screen
                                            break;
                                          case "pending":
                                            Get.to(
                                                RdOrderPendingScreen()); // Navigate to "pending" orders screen
                                            break;
                                          case "processing":
                                            Get.to(
                                                RdOrderProcessingScreen()); // Navigate to "processing" orders screen
                                            break;
                                          // Add more cases for other statuses
                                          case "dispatched":
                                            Get.to(
                                                RdDispatchedScreen()); // Navigate to dispatched orders
                                            break;
                                          case "cancelled":
                                            Get.to(
                                                RdCancelledScreen()); // Navigate to cancelled orders
                                            break;
                                          case "delivered":
                                            Get.to(
                                                RdDeliveredScreen()); // Navigate to delivered orders
                                            break;
                                          default:
                                          // Get.to(YourScreen1()); // Default screen
                                        }
                                      },
                                      child: Chip(
                                        label: Text(
                                          capitalizeFirstLetter(
                                              _filterList[index]),
                                          style: GoogleFonts.roboto(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w500,
                                            color: _selectedIndex == index
                                                ? Colors.white
                                                : Colors
                                                    .black, // Change color when selected
                                          ),
                                        ),
                                        backgroundColor: _selectedIndex == index
                                            ? const Color(0xFF004791)
                                            : Colors.grey[
                                                100], // Change color when selected
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(
                                height: Get.height * 0.6,
                                child: Obx(() {
                                  if (_getRdProductController.productRDList.isEmpty) {
                                    return Center(
                                      child: Text(
                                        'No Orders Found',
                                        style: GoogleFonts.roboto(fontSize: 14),
                                      ),
                                    );
                                  }

                                  final Set<String> uniqueOrderIds = {};
                                  final List<PlacedOrdersResponse>
                                      uniqueOrders = [];

                                  for (var order in _getRdProductController
                                      .productRDList) {
                                    if (uniqueOrderIds.add(order.id)) {
                                      uniqueOrders.add(order);
                                    }
                                  }

                                  if (uniqueOrders.isEmpty) {
                                    return Center(
                                      child: Text(
                                        'No Orders Found',
                                        style: GoogleFonts.roboto(fontSize: 14),
                                      ),
                                    );
                                  }

                                  return ListView.builder(
                                    padding: EdgeInsets.zero,
                                    shrinkWrap: true,
                                    itemCount: uniqueOrders.length,
                                    itemBuilder: (context, index) {
                                      final order = uniqueOrders[index];

                                      // Combine product names into a single string
                                      final productNames = order.orderItem
                                          .map((item) =>
                                              capitalizeFirstLetter(item.name))
                                          .join(', ');

                                      return Padding(
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 8),
                                        child: Card(
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Padding(
                                                padding:
                                                    const EdgeInsets.fromLTRB(
                                                        16, 8, 8, 0),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Text("Order ID: ",
                                                        style:
                                                            GoogleFonts.roboto(
                                                                fontSize: 14,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold)),
                                                    Text("${order.uniqueId}")
                                                  ],
                                                ),
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.fromLTRB(
                                                        16, 8, 8, 0),
                                                child: Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment
                                                          .start, // Aligns the Column to the top of the Text
                                                  children: [
                                                    Text(
                                                      "Product Names: ",
                                                      style: GoogleFonts.roboto(
                                                        fontSize: 14,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                      ),
                                                    ),
                                                    Expanded(
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start, // Aligns text to the right within the Column
                                                        children: [
                                                          const SizedBox(
                                                              height:
                                                                  4), // Adds a small space between the label and the product names
                                                          for (int i = 0;
                                                              i <
                                                                  productNames
                                                                      .split(
                                                                          ",")
                                                                      .length;
                                                              i++)
                                                            Text(
                                                              '${i + 1}. ${productNames.split(",")[i].trim()}', // Adds index and trims whitespace
                                                              textAlign: TextAlign
                                                                  .left, // Aligns text to the right
                                                              style: GoogleFonts
                                                                  .roboto(
                                                                fontSize: 14,
                                                              ),
                                                            ),
                                                        ],
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.fromLTRB(
                                                        16, 8, 8, 0),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Text("Order Value: ",
                                                        style:
                                                            GoogleFonts.roboto(
                                                                fontSize: 14,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold)),
                                                    Text("${order.grandTotal}")
                                                  ],
                                                ),
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.fromLTRB(
                                                        16, 8, 8, 0),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Text("Order Date: ",
                                                        style:
                                                            GoogleFonts.roboto(
                                                                fontSize: 14,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold)),
                                                    Text(formatDate(
                                                        "${order.createdAt}"))
                                                  ],
                                                ),
                                              ),
                                              Padding(
                                                padding:
                                                    const EdgeInsets.fromLTRB(
                                                        16, 8, 8, 8),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Text("Status: ",
                                                        style:
                                                            GoogleFonts.roboto(
                                                                fontSize: 14,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold)),
                                                    Text(capitalizeFirstLetter(
                                                        "${order.status}"))
                                                  ],
                                                ),
                                              ),
                                              SizedBox(
                                                width: Get.width * 0.4,
                                                child: Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: ElevatedButton(
                                                    onPressed: ()
                                                    async {
                                                      onOrderTap(index);
                                                    },
                                                   // =>
                                                       // Get.to(() =>
                                                       //      RdOrderDetailScreen(
                                                       //  placedOrderList: _getRdProductController.productRDList[index])), // Navigate to detail screen
                                                    style: ElevatedButton
                                                        .styleFrom(
                                                      foregroundColor:
                                                          Colors.white,
                                                      backgroundColor:
                                                          const Color(
                                                              0xFF004791),
                                                      shape:
                                                          RoundedRectangleBorder(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          10)),
                                                    ),
                                                    child: Text("View Details",
                                                        style:
                                                            GoogleFonts.roboto(
                                                                fontSize: 14,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .w400)),
                                                  ),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      );
                                    },
                                  );
                                }),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
