import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:grocery_app/src/common_widget/network_image.dart';
import 'package:grocery_app/src/common_widget/textfield_widget.dart';
import 'package:grocery_app/src/core/routes/routes.dart';
import 'package:grocery_app/src/logic/provider/addTocart_provider.dart';
import 'package:grocery_app/src/logic/provider/bottom_navbar_provider.dart';
import 'package:grocery_app/src/logic/provider/home_provider.dart';
import 'package:grocery_app/src/ui/bestdeal/bestdeal_screen.dart';

import 'package:grocery_app/src/ui/widgets/custom_icon_button.dart';
import 'package:grocery_app/src/ui/widgets/elevated_button.dart';
import 'package:grocery_app/utils/constants/assets_constant.dart';
import 'package:grocery_app/utils/constants/color_constant.dart';
import 'package:grocery_app/utils/constants/shared_pref_utils.dart';
import 'package:grocery_app/utils/constants/string_constant.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:grocery_app/utils/extensions/uicontext.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:skeletonizer/skeletonizer.dart';

class Mycart extends StatefulWidget {
  const Mycart({super.key});

  @override
  State<Mycart> createState() => _MycartState();
}

class _MycartState extends State<Mycart> {
  @override
  void initState() {
    Provider.of<AddtocartProvider>(context, listen: false)
        .getItemCards(context);

    Provider.of<AddtocartProvider>(context, listen: false)
        .getCurrentLocation(context);
    Provider.of<AddtocartProvider>(context, listen: false).getAddress(context);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: Center(
          child: const Text(
            'Cart 🛒',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              cartItems(),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  "Before you checkout",
                  style: context.customExtraBold(Colors.black, 18),
                ),
              ),
              relatedProduct(),
              const SizedBox(
                height: 15,
              ),
              Divider(),
              cartPlace(),
            ],
          ),
        ),
      ),
    );
  }

  Widget relatedProduct() {
    return Consumer<ProductProvider>(builder: (context, provider, child) {
      if (provider.isBestdealingloading) {
        return Center(child: CircularProgressIndicator());
      } else if (provider.bestdeal.isEmpty) {
        return Center(child: Text('No products available'));
      } else {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.28,
          child: ListView.builder(
            itemCount: provider.bestdeal.length,
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              var bestdealproduct = provider.bestdeal[index];
              double cardWidth =
                  MediaQuery.of(context).size.width * 0.4; // Dynamic width

              return InkWell(
                onTap: () {
                  context.push(MyRoutes.PRODUCTDETAILS,
                      extra: bestdealproduct.id);
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 10, bottom: 5, top: 5),
                  child: Container(
                    width: cardWidth,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(15),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          blurRadius: 1,
                          offset: const Offset(5, 5),
                        ),
                      ],
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(5),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Center(
                            child: Container(
                              height: MediaQuery.of(context).size.height * 0.12,
                              width: cardWidth * 0.9,
                              decoration: BoxDecoration(
                                color: APPCOLOR.bgGrey,
                                borderRadius: BorderRadius.circular(15),
                              ),
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  AppNetworkImage(
                                    height: MediaQuery.of(context).size.height *
                                        0.08,
                                    width: cardWidth * 0.7,
                                    imageUrl: bestdealproduct
                                            .productImages?.first?.url ??
                                        "",
                                    backGroundColor: Colors.transparent,
                                  ),
                                  // Positioned(
                                  //   right: 5,
                                  //   top: 5,
                                  //   child: InkWell(
                                  //     onTap: () async {
                                  //       if (await SharedPrefUtils.getToken() !=
                                  //           null) {
                                  //         provider.toggleWishlist(
                                  //             context, bestdealproduct.id!);
                                  //       } else {
                                  //         context.push(MyRoutes.LOGIN);
                                  //       }
                                  //     },
                                  //     child: Icon(
                                  //       provider.wishlist
                                  //               .contains(bestdealproduct.id)
                                  //           ? Icons.favorite
                                  //           : Icons.favorite_border,
                                  //       color: provider.wishlist
                                  //               .contains(bestdealproduct.id)
                                  //           ? Colors.red
                                  //           : Colors.grey,
                                  //     ),
                                  //   ),
                                  // ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.01,
                          ),
                          Text(
                            bestdealproduct.name ?? "",
                            textAlign: TextAlign.left,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style:
                                context.customMedium(APPCOLOR.balck1A1A1A, 14),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.005,
                          ),
                          Text(
                            bestdealproduct.unit ?? "",
                            textAlign: TextAlign.left,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: context.customMedium(
                              Colors.grey.withOpacity(0.8),
                              12,
                            ),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.005,
                          ),
                          const Spacer(),
                          Row(
                            children: [
                              Row(
                                children: [
                                  Text(
                                    "\$${bestdealproduct.discountPrice ?? ""}  ",
                                    textAlign: TextAlign.left,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: context.customSemiBold(
                                        Colors.black, 12),
                                  ),
                                  Text(
                                    "\$${bestdealproduct.basePrice ?? ""}",
                                    textAlign: TextAlign.left,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: context
                                        .customMedium(
                                          Colors.grey.withOpacity(0.8),
                                          12,
                                        )
                                        .copyWith(
                                          decoration:
                                              TextDecoration.lineThrough,
                                        ),
                                  ),
                                ],
                              ),
                              const Spacer(),
                              Align(
                                alignment: Alignment.centerRight,
                                child: GestureDetector(
                                  onTap: () async {
                                    if (await SharedPrefUtils.getToken() !=
                                        null) {
                                      await provider.addToCart(
                                          context, bestdealproduct.id!, 1);

                                      context
                                          .read<AddtocartProvider>()
                                          .getItemCards(context);
                                    } else {
                                      context.push(MyRoutes.SIGNUP);
                                    }
                                  },
                                  child: Container(
                                    height: MediaQuery.of(context).size.height *
                                        0.035,
                                    width:
                                        MediaQuery.of(context).size.width * 0.1,
                                    decoration: BoxDecoration(
                                      color: APPCOLOR.lightGreen,
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    child: Center(
                                      child: provider.isLoading[
                                                  bestdealproduct.id] ??
                                              false
                                          ? Padding(
                                              padding:
                                                  const EdgeInsets.all(8.0),
                                              child: Container(
                                                height: 10,
                                                width: 10,
                                                child:
                                                    CircularProgressIndicator(
                                                        color: Colors.white,
                                                        strokeWidth: 2),
                                              ),
                                            )
                                          : Text(
                                              'Add',
                                              style: context.customRegular(
                                                  Colors.white, 12),
                                            ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      }
    });
  }

  double calculateDiscountPercentage(double basePrice, double discountPrice) {
    print(
        "Base Price (Before Discount): $basePrice, Discount Price (After Discount): $discountPrice");

    if (basePrice <= 0 || discountPrice <= 0 || discountPrice > basePrice) {
      print("Error: Invalid price values.");
      return 0;
    }

    double discountAmount = basePrice - discountPrice;
    double discountPercentage = (discountAmount / basePrice) * 100;

    return discountPercentage;
  }

  Widget cartItems() {
    return Consumer<AddtocartProvider>(builder: (context, provider, child) {
      if (provider.isLoaddcartItem) {
        return Skeletonizer(
          enabled: provider.isLoaddcartItem,
          child: ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            separatorBuilder: (_, index) => Padding(
              padding: EdgeInsets.only(top: 12.h, bottom: 24.h),
              child: const Divider(thickness: 1),
            ),
            itemCount: 3, // Display 3 skeleton items
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: 60.w,
                      height: 70.h,
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                    16.horizontalSpace,
                    Container(
                      width: 150.w,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 120.w,
                            height: 14.h,
                            color: Colors.grey[300],
                          ),
                          5.verticalSpace,
                          Container(
                            width: 80.w,
                            height: 14.h,
                            color: Colors.grey[300],
                          ),
                          5.verticalSpace,
                          Row(
                            children: [
                              Container(
                                width: 40.w,
                                height: 14.h,
                                color: Colors.grey[300],
                              ),
                              10.horizontalSpace,
                              Container(
                                width: 40.w,
                                height: 14.h,
                                color: Colors.grey[300],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Row(
                          children: [
                            Container(
                              width: 14.w,
                              height: 14.h,
                              color: Colors.grey[300],
                            ),
                            5.horizontalSpace,
                            Container(
                              width: 14.w,
                              height: 14.h,
                              color: Colors.grey[300],
                            ),
                            5.horizontalSpace,
                            Container(
                              width: 14.w,
                              height: 14.h,
                              color: Colors.grey[300],
                            ),
                          ],
                        ),
                        Gap(20),
                        Container(
                          height: 25,
                          width: 70,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            color: Colors.grey[300],
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              );
            },
          ),
        );
      } else if (provider.allitem == null ||
          provider.allitem.items == null ||
          provider.allitem.items!.isEmpty) {
        return Center(child: Text('🛒 Your Front Shop Cart is empty'));
      } else {
        return ListView.separated(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          separatorBuilder: (_, index) => Padding(
            padding: EdgeInsets.only(top: 12.h, bottom: 24.h),
            child: const Divider(thickness: 1),
          ),
          itemCount: provider.allitem.items!.length,
          itemBuilder: (context, index) {
            var items = provider.allitem.items![index];

            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.greenAccent.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(5),
                    ),
                    child: AppNetworkImage(
                      width: 60.w,
                      height: 70.h,
                      imageUrl: items.product!.productImages!.first.url ?? " ",
                      backGroundColor: APPCOLOR.bgGrey,
                      radius: 10,
                    ),
                  ),
                  16.horizontalSpace,
                  Container(
                    width: 150.w,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          items.product!.name ?? "",
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
                        ),
                        5.verticalSpace,
                        Text(
                          items.product!.unit ?? "",
                          style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
                        ),
                        Row(
                          children: [
                            Text(
                              "\$${items.product!.discountPrice ?? ""}  ",
                              textAlign: TextAlign.left,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: context.customSemiBold(Colors.black, 12),
                            ),
                            Text(
                              "\$${items.product!.basePrice ?? ""}",
                              textAlign: TextAlign.left,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: context
                                  .customMedium(
                                    Colors.grey.withOpacity(0.8),
                                    12,
                                  )
                                  .copyWith(
                                    decoration: TextDecoration.lineThrough,
                                  ),
                            ),
                            SizedBox(width: 10),
                            Container(
                              // padding: EdgeInsets.symmetric(
                              //     horizontal: 6, vertical: 2),
                              // decoration: BoxDecoration(
                              //   color: Colors.green,
                              //   borderRadius: BorderRadius.circular(5),
                              // ),
                              child: Text(
                                  "${calculateDiscountPercentage(double.parse(items.product!.basePrice.toString()), double.parse(items.product!.discountPrice.toString()))}%off",
                                  style: TextStyle(
                                      color: Colors.lightGreen, fontSize: 12)),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  const Spacer(),
                  Column(
                    children: [
                      Row(
                        children: [
                          CustomIconButton(
                            width: 14.w,
                            height: 14.h,
                            onPressed: () async {
                              if (items.quantity! > 1) {
                                await provider.decreaseCartQuantity(
                                    context,
                                    items.id!,
                                    int.parse(items.quantity.toString()) - 1);
                              }
                            },
                            icon: SvgPicture.asset(
                              APPASSETS.removeIcon,
                              fit: BoxFit.none,
                            ),
                            backgroundColor: APPCOLOR.appGreen,
                          ),
                          5.horizontalSpace,
                          Text(
                            items.quantity.toString(),
                            style:
                                context.customMedium(APPCOLOR.balck1A1A1A, 14),
                          ),
                          5.horizontalSpace,
                          CustomIconButton(
                            width: 14.w,
                            height: 14.h,
                            onPressed: () async {
                              await provider.addToCart(
                                  context, items.productId!, 1);

                              // await provider.getItemCards(context);
                            },
                            icon: SvgPicture.asset(
                              APPASSETS.addIcon,
                              fit: BoxFit.none,
                            ),
                            backgroundColor: APPCOLOR.appGreen,
                          ),
                        ],
                      ),
                      Gap(20),
                      InkWell(
                        onTap: () async {
                          provider.deleteItem(context, items.id);
                        },
                        child: Container(
                          height: 25,
                          width: 70,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            shape: BoxShape.rectangle,
                            border: Border.all(
                              color: Colors.blue,
                              width: 2,
                            ),
                          ),
                          child: provider.isRemoveItem[items.id] ?? false
                              ? Center(
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Container(
                                      height: 5,
                                      width: 5,
                                      child: CircularProgressIndicator(
                                          color: Colors.green, strokeWidth: 1),
                                    ),
                                  ),
                                )
                              : Center(child: Text("Delete")),
                        ),
                      )
                    ],
                  )
                ],
              ),
            );
          },
        );
      }
    });
  }

  // Widget relatedProduct() {
  //   return SizedBox(
  //     height: 222,
  //     child: ListView.builder(
  //       itemCount: 5,
  //       scrollDirection: Axis.horizontal,
  //       itemBuilder: (context, index) {
  //         return Padding(
  //           padding: const EdgeInsets.only(right: 10, bottom: 5, top: 5),
  //           child: Container(
  //             height: 215,
  //             width: 150,
  //             decoration: BoxDecoration(
  //                 color: Colors.white,
  //                 borderRadius: BorderRadius.circular(15),
  //                 boxShadow: [
  //                   BoxShadow(
  //                     color: Colors.grey.withOpacity(0.1),
  //                     blurRadius: 1,
  //                     offset: const Offset(5, 5),
  //                   ),
  //                 ]),
  //             child: Padding(
  //               padding: const EdgeInsets.all(5),
  //               child: Column(
  //                 crossAxisAlignment: CrossAxisAlignment.start,
  //                 children: [
  //                   Container(
  //                     height: 100,
  //                     width: 150,
  //                     decoration: BoxDecoration(
  //                         color: APPCOLOR.bgGrey,
  //                         borderRadius: BorderRadius.circular(15)),
  //                     child: const Stack(
  //                       alignment: Alignment.center,
  //                       children: [
  //                         AppNetworkImage(
  //                             height: 70,
  //                             width: 70,
  //                             imageUrl:
  //                                 "https://5.imimg.com/data5/SELLER/Default/2024/2/385126988/OL/DA/VW/8627346/1l-fortune-sunflower-oil.jpg",
  //                             backGroundColor: Colors.transparent),
  //                         Positioned(
  //                             right: 5,
  //                             top: 5,
  //                             child: Icon(Icons.favorite_border))
  //                       ],
  //                     ),
  //                   ),
  //                   Text(
  //                     "Fortune Arhar Dal (Toor Dal)",
  //                     textAlign: TextAlign.left,
  //                     maxLines: 2,
  //                     overflow: TextOverflow.ellipsis,
  //                     style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
  //                   ),
  //                   const SizedBox(
  //                     height: 5,
  //                   ),
  //                   Text(
  //                     "500 ML",
  //                     textAlign: TextAlign.left,
  //                     maxLines: 1,
  //                     overflow: TextOverflow.ellipsis,
  //                     style: context.customMedium(
  //                         Colors.grey.withOpacity(0.8), 12),
  //                   ),
  //                   const SizedBox(
  //                     height: 3,
  //                   ),
  //                   Row(
  //                     children: [
  //                       Expanded(
  //                           child: Row(
  //                         children: [
  //                           Text(
  //                             "\$12",
  //                             textAlign: TextAlign.left,
  //                             maxLines: 1,
  //                             overflow: TextOverflow.ellipsis,
  //                             style: context.customSemiBold(Colors.black, 12),
  //                           ),
  //                           const SizedBox(
  //                             width: 5,
  //                           ),
  //                           Text(
  //                             "\$14",
  //                             textAlign: TextAlign.left,
  //                             maxLines: 1,
  //                             overflow: TextOverflow.ellipsis,
  //                             style: context
  //                                 .customMedium(
  //                                     Colors.grey.withOpacity(0.8), 12)
  //                                 .copyWith(
  //                                   decoration: TextDecoration.lineThrough,
  //                                 ),
  //                           ),
  //                         ],
  //                       )),
  //                       Expanded(
  //                         child: Align(
  //                           alignment: Alignment.centerRight,
  //                           child: Container(
  //                             height: 30,
  //                             width: 50,
  //                             decoration: BoxDecoration(
  //                               color: APPCOLOR.lightGreen,
  //                               borderRadius: BorderRadius.circular(5),
  //                             ),
  //                             child: Center(
  //                                 child: Text(
  //                               'Add',
  //                               style: context.customRegular(Colors.white, 12),
  //                             )),
  //                           ),
  //                         ),
  //                       )
  //                     ],
  //                   ),
  //                 ],
  //               ),
  //             ),
  //           ),
  //         );
  //       },
  //     ),
  //   );
  // }

  // Widget cartItems() {
  //   return Consumer<AddtocartProvider>(builder: (context, provider, child) {
  //     if (provider.isLoaddcartItem) {
  //       return Center(
  //         child: CircularProgressIndicator(
  //           color: Colors.green,
  //         ),
  //       );
  //     } else if (provider.allitem == null) {
  //       return Center(child: Text('🛒 Your Front Shop Cart is empty'));
  //     } else if (provider.allitem.items == null ||
  //         provider.allitem.items!.isEmpty) {
  //       return Center(child: Text('🛒 Your Front Shop Cart is empty'));
  //     } else {
  //       return ListView.separated(
  //         shrinkWrap: true, // Prevents internal scrolling
  //         physics: NeverScrollableScrollPhysics(), // Disables inner scroll
  //         separatorBuilder: (_, index) => Padding(
  //           padding: EdgeInsets.only(top: 12.h, bottom: 24.h),
  //           child: const Divider(thickness: 1),
  //         ),
  //         itemCount: provider.allitem.items!.length,
  //         itemBuilder: (context, index) {
  //           var items = provider.allitem.items![index];

  //           return Padding(
  //             padding: EdgeInsets.symmetric(horizontal: 10.w),
  //             child: Row(
  //               crossAxisAlignment: CrossAxisAlignment.start,
  //               children: [
  //                 Container(
  //                   decoration: BoxDecoration(
  //                     color: Colors.greenAccent.withOpacity(0.1),
  //                     borderRadius: BorderRadius.circular(5),
  //                   ),
  //                   child: AppNetworkImage(
  //                     width: 60.w,
  //                     height: 70.h,
  //                     imageUrl: items.product!.productImages!.first.url ?? " ",
  //                     backGroundColor: APPCOLOR.bgGrey,
  //                     radius: 10,
  //                   ),
  //                 ),
  //                 //  Image.asset(product.image, width: 50.w, height: 40.h),

  //                 16.horizontalSpace,
  //                 Container(
  //                   width: 150.w,
  //                   child: Column(
  //                     crossAxisAlignment: CrossAxisAlignment.start,
  //                     mainAxisAlignment: MainAxisAlignment.start,
  //                     children: [
  //                       Text(
  //                         items.product!.name ?? "",
  //                         maxLines: 2,
  //                         overflow: TextOverflow.ellipsis,
  //                         style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
  //                       ),
  //                       5.verticalSpace,
  //                       Text(
  //                         items.product!.unit ?? "",
  //                         style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
  //                       ),
  //                       Row(
  //                         children: [
  //                           Text(
  //                             "\$${items.product!.discountPrice ?? ""}  ",
  //                             textAlign: TextAlign.left,
  //                             maxLines: 1,
  //                             overflow: TextOverflow.ellipsis,
  //                             style: context.customSemiBold(Colors.black, 12),
  //                           ),
  //                           Text(
  //                             "\$${items.product!.basePrice ?? ""}",
  //                             textAlign: TextAlign.left,
  //                             maxLines: 1,
  //                             overflow: TextOverflow.ellipsis,
  //                             style: context
  //                                 .customMedium(
  //                                   Colors.grey.withOpacity(0.8),
  //                                   12,
  //                                 )
  //                                 .copyWith(
  //                                   decoration: TextDecoration.lineThrough,
  //                                 ),
  //                           ),
  //                         ],
  //                       ),
  //                     ],
  //                   ),
  //                 ),
  //                 const Spacer(),

  //                 Column(
  //                   children: [
  //                     Row(
  //                       children: [
  //                         CustomIconButton(
  //                           width: 14.w,
  //                           height: 14.h,
  //                           onPressed: () {
  //                             // provider.decreaseQuantity(items);
  //                           },
  //                           icon: SvgPicture.asset(
  //                             APPASSETS.removeIcon,
  //                             fit: BoxFit.none,
  //                           ),
  //                           backgroundColor: APPCOLOR.appGreen,
  //                         ),
  //                         5.horizontalSpace,
  //                         Text(
  //                           items.quantity.toString(),
  //                           style:
  //                               context.customMedium(APPCOLOR.balck1A1A1A, 14),
  //                         ),
  //                         5.horizontalSpace,
  //                         CustomIconButton(
  //                           width: 14.w,
  //                           height: 14.h,
  //                           onPressed: () {
  //                             // provider..increaseQuantity(items);
  //                           },
  //                           icon: SvgPicture.asset(
  //                             APPASSETS.addIcon,
  //                             fit: BoxFit.none,
  //                           ),
  //                           backgroundColor: APPCOLOR.appGreen,
  //                         ),
  //                       ],
  //                     ),
  //                     Gap(20),
  //                     InkWell(
  //                       onTap: () {
  //                         provider.deleteItem(context, items.id);
  //                       },
  //                       child: Container(
  //                         height: 25,
  //                         width: 70,
  //                         decoration: BoxDecoration(
  //                           borderRadius: BorderRadius.all(Radius.circular(10)),
  //                           shape: BoxShape.rectangle,
  //                           border: Border.all(
  //                             color: Colors
  //                                 .blue, // Replace with your desired border color
  //                             width: 2, // Border width
  //                           ),
  //                         ),
  //                         child: provider.isRemoveItem[items.id] ?? false
  //                             ? Center(
  //                                 child: Padding(
  //                                   padding: const EdgeInsets.all(8.0),
  //                                   child: Container(
  //                                     height: 5,
  //                                     width: 5,
  //                                     child: CircularProgressIndicator(
  //                                         color: Colors.green, strokeWidth: 1),
  //                                   ),
  //                                 ),
  //                               )
  //                             : Center(child: Text("Delete")),
  //                       ),
  //                     )
  //                   ],
  //                 )
  //               ],
  //             ),
  //           );
  //         },
  //       );
  //     }
  //   });
  // }

  Widget cartPlace() {
    return Consumer<AddtocartProvider>(builder: (context, provider, child) {
      print("jdhfgkdfkjg  ${provider.allitem.createdAt}");
      if (provider.isLoaddcartItem) {
        return Padding(
          padding: const EdgeInsets.only(left: 120),
          child: CircularProgressIndicator(
            color: Colors.white,
          ),
        );
      } else if (provider.allitem == null) {
        return Center(child: Text('🛒 Your Front Shop Cart is empty'));
      } else if (provider.allitem.items == null) {
        return Center(
            child: ElevatedButton(
          style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
          onPressed: () {
            context.read<BottomNavProvider>().setIndex(0);
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Continue Shopping',
                  style: TextStyle(fontSize: 16, color: Colors.white))
            ],
          ),
        ));
      } else {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ListTile(
              leading: Icon(Icons.local_offer, color: Colors.green),
              title: Text('APPLY COUPON',
                  style: TextStyle(fontWeight: FontWeight.bold)),
              trailing: Icon(Icons.arrow_forward_ios),
              onTap: () {
                context.push(MyRoutes.COUPONSSCREEN);
              },
            ),
            SummaryRow(
                label: 'Item Total Price',
                value: '\$${provider.allitem.subtotal}'),
            SummaryRow(label: 'Discount', value: '0.0'),
            SummaryRow(label: 'Delivery Free', value: 'Free', isGreen: true),
            Divider(),
            SummaryRow(
                label: 'Grand Total',
                value: '\$${provider.allitem.subtotal}',
                isBold: true),
            ListTile(
              leading: Icon(Icons.home, color: Colors.green),
              title: provider.isDeliverable
                  ? Text('Delivering to : ${provider.pinCode}')
                  : Text(
                      'Out Of Stock : ${provider.pinCode}',
                      style: TextStyle(color: Colors.red),
                    ),
              trailing: Text('Change', style: TextStyle(color: Colors.blue)),
              onTap: () {
                _showBottomSheet(context);
              },
            ),
            SizedBox(height: 10),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: APPCOLOR.lightGreen),
              onPressed: () {
                if (provider.isDeliverable) {
                  _showAddressBottomSheet(context);
                } else {
                  Fluttertoast.showToast(
                    msg:
                        "Delivery is not available for this pincode. Please try another pincode!",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.BOTTOM,
                    backgroundColor: Colors.red,
                    textColor: Colors.white,
                    fontSize: 14.0,
                  );
                }
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('\$22  Place Order', style: TextStyle(fontSize: 16))
                ],
              ),
            ),
          ],
        );
      }
    });
  }

  void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Consumer<AddtocartProvider>(
            builder: (context, pinProvider, child) {
          return Container(
            padding: EdgeInsets.all(20.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Form(
                  child: Container(
                    width: 200.h,

                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(
                          8), // Border radius for container
                      border: Border.all(color: Colors.grey, width: 1),
                    ), // Border for the container

                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        children: [
                          Expanded(
                            flex: 2,
                            child: Container(
                              height: 20.h,
                              child: TextFormField(
                                controller: pinProvider.checkPinCode,
                                maxLength: 6,
                                keyboardType: TextInputType.phone,
                                onChanged: (value) {},
                                decoration: InputDecoration(
                                  hintText: 'Enter PIN',
                                  counterText: "",
                                  border: InputBorder
                                      .none, // Remove the inner border
                                ),
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Cannot be empty';
                                  } else if (!RegExp(r'^[0-9]{4,6}$')
                                      .hasMatch(value)) {
                                    return 'Enter a valid PIN (4-6 digits)';
                                  }
                                  return null;
                                },
                              ),
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              pinProvider.checkPin(
                                  context, pinProvider.checkPinCode.text);
                            },
                            child: Expanded(
                                flex: 1,
                                child: pinProvider.ischeckpin
                                    ? Center(
                                        child: CircularProgressIndicator(
                                          color: APPCOLOR.lightGreen,
                                        ),
                                      )
                                    : Text(
                                        "Check PIN",
                                        style: TextStyle(
                                            fontSize: 15,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black),
                                      )),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                if (!pinProvider.isDeliverable) ...{
                  Text(
                    'Delivery is not available for this pincode. Please try another pincode.',
                    style: TextStyle(color: Colors.red, fontSize: 10),
                  ),
                } else ...{
                  Text(
                    'Delivery available for this pincode. Submit now.',
                    style: TextStyle(color: Colors.lightGreen, fontSize: 10),
                  ),
                },
                Gap(10.h),
                Center(
                  child: SizedBox(
                    child: SizedBox(
                      width: double.infinity,
                      child: ButtonElevated(
                          text: 'Submit',
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          backgroundColor: APPCOLOR.appGreen),
                    ),
                  ),
                ),
              ],
            ),
          );
        });
      },
    );
  }

  void _showAddressBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      isDismissible: false, // Allows tap outside to close
      enableDrag: true, // Enables swipe-down to dismiss
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),

      builder: (context) {
        return AddressBottomSheet();
      },
    );
  }
}

class AddressBottomSheet extends StatefulWidget {
  @override
  _AddressBottomSheetState createState() => _AddressBottomSheetState();
}

class _AddressBottomSheetState extends State<AddressBottomSheet> {
  // String selectedAddress = "Home";

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding:
          EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        padding: EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Select an Address",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            SizedBox(height: 10),
            _buildAddressTile(context),
            SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: () {
                context.push(MyRoutes.ADDRESSS);
              },
              icon: Icon(Icons.add, color: Colors.white),
              label: Text(
                "Add New Address",
                style: TextStyle(color: Colors.white, fontSize: 15),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                minimumSize: Size(double.infinity, 50),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: () {},
              label: Text(
                "Continue",
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                minimumSize: Size(double.infinity, 50),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
              ),
            ),
            SizedBox(height: 10),
          ],
        ),
      ),
    );
  }

  Widget _buildAddressTile(BuildContext context) {
    return Consumer<AddtocartProvider>(
      builder: (context, addressProvider, child) {
        return addressProvider.addresslist.isEmpty
            ? SizedBox.shrink()
            : ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: addressProvider.addresslist.length,
                itemBuilder: (context, index) {
                  var address = addressProvider.addresslist[index];

                  return Card(
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    child: ListTile(
                      leading: Radio(
                        value: address.id ?? "",
                        groupValue: addressProvider
                            .selectedAddress, // Use provider's value
                        activeColor: Colors.green,
                        onChanged: (value) {
                          addressProvider.selectAddress(value.toString());
                        },
                      ),
                      title: Text(
                        address.addressType ?? "",
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      subtitle: Text(address.addressLine +
                              " " +
                              address.landmark +
                              " " +
                              address.city ??
                          ""),
                    ),
                  );
                },
              );
      },
    );
  }
}

class SummaryRow extends StatelessWidget {
  final String label, value;
  final bool isGreen, isBold;

  SummaryRow(
      {required this.label,
      required this.value,
      this.isGreen = false,
      this.isBold = false});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label,
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: isBold ? FontWeight.bold : FontWeight.normal)),
          Text(value,
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: isBold ? FontWeight.bold : FontWeight.normal,
                  color: isGreen ? Colors.green : Colors.black)),
        ],
      ),
    );
  }
}
