import 'package:cheminova/screens/order/checkout_screen.dart';
import 'package:cheminova/widgets/my_drawer.dart';
import 'package:cheminova/widgets/product_card.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 '../../models/oder_place_model.dart';
import '../../models/product_model1.dart';

// CartScreen represents the cart view in the application, where users can review
// products they have added, select/deselect them, and proceed to checkout.
class CartScreen extends StatefulWidget {
  Product? productModel; // Optional product model to add a product directly to the cart.
  PlacedOrderModel? placedOrder; // Optional order placement model.

  CartScreen({super.key, this.productModel, this.placedOrder});

  @override
  State<CartScreen> createState() => _CartScreenState();
}

class _CartScreenState extends State<CartScreen> {
  // CartController handles cart-related logic such as adding/removing products, selections, and totals.
  final CartController _cartController = Get.find<CartController>();

  bool _selectAll = true; // Boolean flag to determine if all products are selected by default.

  @override
  void initState() {
    super.initState();

    // If a product model is passed when navigating to this screen, add it to the cart.
    if (widget.productModel != null) {
      _cartController.addToCart(widget.productModel!);
    }

    // Initialize product selections to ensure all products are selected by default.
    _cartController.initializeSelections();

    // Check if all products are selected and update the _selectAll flag accordingly.
    _checkIfAllSelected();
  }

  // Toggles the selection of all products in the cart.
  void _toggleSelectAll(bool? value) {
    setState(() {
      _selectAll = value ?? false; // Update _selectAll based on the checkbox value.
      _cartController.selectAllProducts(_selectAll); // Select or deselect all products.
    });
  }

  // Check if all products in the cart are selected. Updates the _selectAll flag.
  void _checkIfAllSelected() {
    setState(() {
      // If every product in the cart is selected, _selectAll is set to true.
      _selectAll = _cartController.cartList.every(
            (product) => _cartController.selectedProducts.contains(product),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,

      // Transparent AppBar with a menu icon and back button.
      appBar: AppBar(
        backgroundColor: Colors.transparent, // Transparent background.
        elevation: 0, // No elevation.
        leading: Builder(
          builder: (context) {
            return GestureDetector(
              onTap: () => Scaffold.of(context).openDrawer(), // Open the drawer on tap.
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: SvgPicture.asset(
                  'assets/svg/menu.svg', // SVG asset for the menu icon.
                ),
              ),
            );
          },
        ),
        actions: [
          // Back button to navigate to the previous screen.
          GestureDetector(
            onTap: () => Get.back(), // Go back on tap.
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg', // SVG asset for the back icon.
              ),
            ),
          ),
        ],
        title: const Center(
          child: Text(
            "Cart", // Title for the AppBar.
          ),
        ),
      ),

      drawer: const MyDrawer(), // Drawer menu.

      // Stack for the background image and the content above it.
      body: Stack(
        fit: StackFit.expand, // Ensure the background image fills the entire screen.
        children: [
          // Background image that covers the entire screen.
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover, // Cover the entire screen with the image.
          ),

          // SafeArea ensures content is within safe device boundaries.
          SafeArea(
            // Obx listens to changes in the cartList and updates the UI.
            child: Obx(() {
              // If the cart is empty, show an empty cart message and image.
              if (_cartController.cartList.isEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/images/cart.png', // Display an empty cart image.
                        width: Get.width * 0.5,
                        height: Get.width * 0.5,
                      ),
                      const SizedBox(height: 20),
                      Text(
                        'Your Cart is empty', // Message indicating the cart is empty.
                        style: GoogleFonts.roboto(
                          fontSize: 24,
                          fontWeight: FontWeight.w500,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                );
              }

              // If there are items in the cart, show the cart list and summary.
              return Column(
                children: [
                  SizedBox(
                    height: Get.height * 0.02,
                  ),

                  // Card widget for displaying the cart details and selection options.
                  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: [
                          // Row for "Select All" checkbox and label.
                          Row(
                            children: [
                              Checkbox(
                                value: _selectAll, // Checkbox value linked to _selectAll flag.
                                onChanged: _toggleSelectAll, // Toggle all selections when changed.
                              ),
                              Text(
                                "Select All", // Label for the select all checkbox.
                                style: GoogleFonts.roboto(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),

                          // List of products in the cart.
                          SizedBox(
                            height: Get.height * 0.6,
                            child: ListView.builder(
                              padding: EdgeInsets.zero,
                              itemCount: _cartController.cartList.length, // Number of items in the cart.
                              itemBuilder: (context, index) {
                                return Row(
                                  children: [
                                    // Checkbox for individual product selection.
                                    Checkbox(
                                      value: _cartController.selectedProducts.contains(
                                          _cartController.cartList[index]),
                                      onChanged: (value) {
                                        _cartController.toggleProductSelection(
                                          _cartController.cartList[index],
                                          value!, // Toggle product selection.
                                        );
                                        _checkIfAllSelected(); // Recheck if all products are selected.
                                      },
                                    ),

                                    // ProductCard displaying product details in the cart.
                                    Expanded(
                                      child: ProductCard(
                                        productModel: _cartController.cartList[index],
                                        isInCart: true, // Indicates this product is in the cart.
                                        placedOrder: widget.placedOrder,
                                      ),
                                    ),
                                  ],
                                );
                              },
                            ),
                          ),
                          const SizedBox(height: 10),

                          // Row displaying the subtotal amount.
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "Subtotal ",
                                style: GoogleFonts.roboto(
                                  fontSize: 15,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              // Display the subtotal using an Obx to update automatically.
                              Obx(() => Text("₹ ${_cartController.subtotal.value.toStringAsFixed(2)}")),
                            ],
                          ),

                          // Row displaying the GST amount.
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "GST  ",
                                style: GoogleFonts.roboto(
                                  fontSize: 15,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Obx(() => Text("₹ ${_cartController.gstTotal.value.toStringAsFixed(2)}")),
                            ],
                          ),

                          // Row displaying the total amount (subtotal + GST).
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "Total Amount ",
                                style: GoogleFonts.roboto(
                                  fontSize: 15,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Obx(() => Text("₹ ${_cartController.grandTotal.value.toStringAsFixed(2)}")),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),

                  SizedBox(height: Get.height * 0.020),

                  // Button to proceed to the checkout screen.
                  SizedBox(
                    width: Get.width * 0.9,
                    height: Get.height * 0.06,
                    child: ElevatedButton(
                      onPressed: () => Get.to(() => CheckoutScreen(
                        selectedProducts: _cartController.selectedProducts, // Pass selected products to CheckoutScreen.
                      )),
                      style: ElevatedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: const Color(0xFF00784C), // Green button for checkout.
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      child: Text(
                        "Proceed to Checkout",
                        style: GoogleFonts.roboto(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }),
          ),
        ],
      ),
    );
  }
}






// import 'package:cheminova/models/oder_place_model.dart';
// import 'package:cheminova/models/product_model.dart';
// import 'package:cheminova/screens/order/checkout_screen.dart';
// import 'package:cheminova/widgets/my_drawer.dart';
// import 'package:cheminova/widgets/product_card.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 '../../models/product_model1.dart';
//
// class CartScreen extends StatefulWidget {
//   Product? productModel;
//   PlacedOrderModel? placedOrder;
//
//   CartScreen({super.key, this.productModel, this.placedOrder});
//
//   @override
//   State<CartScreen> createState() => _CartScreenState();
// }
//
// class _CartScreenState extends State<CartScreen> {
//   final CartController _cartController = Get.find<CartController>();
//
//   bool _selectAll = false; // State to track "Select All" checkbox
//
//   @override
//   void initState() {
//     super.initState();
//     if (widget.productModel != null) {
//       _cartController.addToCart(widget.productModel!);
//     }
//   }
//
//   void _toggleSelectAll(bool? value) {
//     setState(() {
//       _selectAll = value ?? false;
//       _cartController.cartList.forEach((product) {
//         _cartController.toggleProductSelection(product, _selectAll);
//       });
//     });
//   }
//
//   @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: Center(
//           child: const Text(
//             "Cart",
//           ),
//         ),
//       ),
//       drawer: const MyDrawer(),
//       body: Stack(
//         fit: StackFit.expand,
//         children: [
//           Image.asset(
//             'assets/images/image_1.png',
//             fit: BoxFit.cover,
//           ),
//           SafeArea(
//             child: Obx(() {
//               if (_cartController.cartList.isEmpty) {
//                 return Center(
//                   child: Column(
//                     mainAxisAlignment: MainAxisAlignment.center,
//                     children: [
//                       Image.asset(
//                         'assets/images/cart.png',
//                         width: Get.width * 0.5,
//                         height: Get.width * 0.5,
//                       ),
//                       const SizedBox(height: 20),
//                       Text(
//                         'Your Cart is empty',
//                         style: GoogleFonts.roboto(
//                           fontSize: 24,
//                           fontWeight: FontWeight.w500,
//                           color: Colors.white,
//                         ),
//                       ),
//                     ],
//                   ),
//                 );
//               }
//               return 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: [
//                           // "Select All" Checkbox
//                           Row(
//                             children: [
//                               Checkbox(
//                                 value: _selectAll,
//                                 onChanged: _toggleSelectAll,
//                               ),
//                               Text(
//                                 "Select All",
//                                 style: GoogleFonts.roboto(
//                                   fontSize: 16,
//                                   fontWeight: FontWeight.w500,
//                                 ),
//                               ),
//                             ],
//                           ),
//                           SizedBox(
//                             height: Get.height * 0.6,
//                             child: ListView.builder(
//                               padding: EdgeInsets.zero,
//                               itemCount: _cartController.cartList.length,
//                               itemBuilder: (context, index) {
//                                 return Row(
//                                   children: [
//                                     Checkbox(
//                                       value: _cartController
//                                           .cartList[index].selected,
//                                       onChanged: (value) {
//                                         setState(() {
//
//                                         });
//                                         _cartController.toggleProductSelection(
//                                             _cartController.cartList[index],
//                                             value!);
//                                       },
//                                     ),
//                                     Expanded(
//                                       child: ProductCard(
//                                         productModel:
//                                         _cartController.cartList[index],
//                                         isInCart: true,
//                                         placedOrder: widget.placedOrder,
//                                       ),
//                                     ),
//                                   ],
//                                 );
//                               },
//                             ),
//                           ),
//                           const SizedBox(height: 10),
//                           Row(
//                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                             children: [
//                               Text(
//                                 "Subtotal ",
//                                 style: GoogleFonts.roboto(
//                                   fontSize: 15,
//                                   color: Colors.black,
//                                   fontWeight: FontWeight.bold,
//                                 ),
//                               ),
//                               Obx(() => Text("₹ ${_cartController.subtotal.value}")),
//                             ],
//                           ),
//                           Row(
//                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                             children: [
//                               Text(
//                                 "GST  ",
//                                 style: GoogleFonts.roboto(
//                                   fontSize: 15,
//                                   color: Colors.black,
//                                   fontWeight: FontWeight.bold,
//                                 ),
//                               ),
//                               Obx(() => Text("₹ ${_cartController.gstTotal.value}")),
//                             ],
//                           ),
//                           Row(
//                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                             children: [
//                               Text(
//                                 "Total Amount ",
//                                 style: GoogleFonts.roboto(
//                                   fontSize: 15,
//                                   color: Colors.black,
//                                   fontWeight: FontWeight.bold,
//                                 ),
//                               ),
//                               Obx(() => Text("₹ ${_cartController.grandTotal.value}")),
//                             ],
//                           ),
//                         ],
//                       ),
//                     ),
//                   ),
//                   SizedBox(height: Get.height * 0.020),
//                   SizedBox(
//                     width: Get.width * 0.9,
//                     height: Get.height * 0.06,
//                     child: ElevatedButton(
//                       onPressed: () => Get.to(() => CheckoutScreen(
//                         productModel: widget.productModel,
//                       )),
//                       style: ElevatedButton.styleFrom(
//                         foregroundColor: Colors.white,
//                         backgroundColor: const Color(0xFF00784C),
//                         shape: RoundedRectangleBorder(
//                           borderRadius: BorderRadius.circular(10),
//                         ),
//                       ),
//                       child: Text(
//                         "Proceed to Checkout",
//                         style: GoogleFonts.roboto(
//                           fontSize: 16,
//                           fontWeight: FontWeight.w600,
//                         ),
//                       ),
//                     ),
//                   ),
//                 ],
//               );
//             }),
//           ),
//         ],
//       ),
//     );
//   }
// }
