
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';

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 = true; // Default to true to select all products

  @override
  void initState() {
    super.initState();
    if (widget.productModel != null) {
      _cartController.addToCart(widget.productModel!);
    }
    // Ensure all products are pre-selected by default
    _cartController.initializeSelections();
    _checkIfAllSelected(); // Check if all products are selected by default
  }

  void _toggleSelectAll(bool? value) {
    setState(() {
      _selectAll = value ?? false;
      _cartController.selectAllProducts(_selectAll);
    });
  }

  void _checkIfAllSelected() {
    // This function checks if all items are selected or not and updates _selectAll
    setState(() {
      _selectAll = _cartController.cartList.every(
            (product) => _cartController.selectedProducts.contains(product),
      );
    });
  }

  @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(
            "Cart",
          ),
        ),
      ),
      drawer:  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.selectedProducts.contains(
                                          _cartController.cartList[index]),
                                      onChanged: (value) {
                                        _cartController.toggleProductSelection(
                                          _cartController.cartList[index],
                                          value!,
                                        );
                                        _checkIfAllSelected(); // Check if all are selected after each toggle
                                      },
                                    ),
                                    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(
                        selectedProducts: _cartController.selectedProducts,
                      )),
                      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,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }),
          ),
        ],
      ),
    );
  }
}





// 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,
//                         ),
//                       ),
//                     ),
//                   ),
//                 ],
//               );
//             }),
//           ),
//         ],
//       ),
//     );
//   }
// }
