import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.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/card_checkout/card_checkout_screen.dart';
import 'package:grocery_app/src/ui/data_notfound.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';
import 'package:url_launcher/url_launcher.dart';

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

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

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

      addToCartProvider.getItemCards(context);
      addToCartProvider.offerCoupon(context);
      addToCartProvider.getCurrentLocation(context);
      addToCartProvider.getAddress(context);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        title: Center(
          child: const Text(
            'My 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(),
              bannerview(),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  "Before you checkout",
                  style: context.customExtraBold(Colors.black, 18),
                ),
              ),
              relatedProduct(),
              const SizedBox(
                height: 15,
              ),
              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(''));
      } else {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.28,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: provider.bestdeal.length,
            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: {
                      "id": bestdealproduct.id,
                      "quantity": 1,
                      "price": bestdealproduct.discountPrice,
                    },
                  );
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 5, 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: 1,
                                    bottom: 0,
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 6, vertical: 2),
                                      decoration: BoxDecoration(
                                        color: Colors.red,
                                        borderRadius: BorderRadius.circular(5),
                                      ),
                                      child: Center(
                                        child: Text(
                                            "${calculateDiscountPercentage(double.parse(bestdealproduct!.basePrice), double.parse(bestdealproduct!.discountPrice))}% OFF",
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 12)),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                          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 ?? ""}",
                                    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.028,
                                    // 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),
                                            ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      }
    });
  }

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

    print("kjhfjhdsfghjk  ${discountPercentage.round()}");
    return discountPercentage.round();
  }

  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: 2,
            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 DataNotFound(
          imagePath: 'assets/images/cartempty.jpg',
          message: "",
          width: 100.w,
          height: 100.h,
        );
      } else {
        return ListView.separated(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          separatorBuilder: (_, index) => Padding(
            padding: EdgeInsets.only(top: 8.h, bottom: 8.h),
            // child: const Divider(thickness: 1),
          ),
          itemCount: provider.allitem.items!.length,
          itemBuilder: (context, index) {
            var items = provider.allitem.items![index];

            return InkWell(
              onTap: () {
                context.push(
                  MyRoutes.PRODUCTDETAILS,
                  extra: {
                    "id": items.product!.id,
                    "quantity": items.quantity,
                    "price": items.product!.discountPrice,
                  },
                );
              },
              child: 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),
                          ),
                          2.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)),
                              ),
                            ],
                          ),
                          Gap(5),
                          InkWell(
                            onTap: () {
                              showReturnPolicyBottomSheet(context);
                            },
                            child: Text("3 days Return & Exchange ",
                                style: TextStyle(
                                    color: Colors.green, fontSize: 1)),
                          ),
                        ],
                      ),
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Container(
                          height: 25,
                          width: 70,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(7)),
                            shape: BoxShape.rectangle,
                            border: Border.all(
                              color: APPCOLOR.lightGreen,
                              width: 1,
                            ),
                          ),
                          child: Center(
                            child: Row(
                              //   crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                InkWell(
                                  onTap: () async {
                                    if (items.quantity! > 1) {
                                      await provider.decreaseCartQuantity(
                                          context,
                                          items.id!,
                                          int.parse(items.quantity.toString()) -
                                              1);
                                    }
                                  },
                                  child: Icon(
                                    Icons.remove,
                                    size: 15,
                                    color: APPCOLOR.lightGreen,
                                  ),
                                ),
                                // IconButton(
                                //   // 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: Icon(Icons.minimize_rounded),
                                //   iconSize: 10,
                                // ),
                                Gap(10),
                                Text(
                                  items.quantity.toString(),
                                  style: context.customMedium(
                                      APPCOLOR.balck1A1A1A, 14),
                                ),
                                Gap(10),
                                InkWell(
                                  onTap: () async {
                                    await provider.addToCart(
                                        context, items.productId!, 1);
                                  },
                                  child: Icon(
                                    Icons.add,
                                    size: 15,
                                    color: APPCOLOR.lightGreen,
                                  ),
                                ),
                                // IconButton(
                                //   onPressed: () async {
                                //     await provider.addToCart(
                                //         context, items.productId!, 1);

                                //     // await provider.getItemCards(context);
                                //   },
                                //   icon: Icon(Icons.add),
                                //   iconSize: 10,
                                // ),
                              ],
                            ),
                          ),
                        ),
                        Gap(20),
                        InkWell(
                          onTap: () async {
                            provider.deleteItem(context, items.id);
                          },
                          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")),
                        )
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        );
      }
    });
  }

  void showReturnPolicyBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      backgroundColor: Colors.white,
      builder: (context) {
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Close Button
              Align(
                alignment: Alignment.topRight,
                child: IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ),

              // Title
              Text(
                "3 days Return & Exchange",
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10),

              // Table Headers
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                      child: Text("Return Reason",
                          style: TextStyle(fontWeight: FontWeight.bold))),
                  Expanded(
                      child: Text("Return Period",
                          style: TextStyle(fontWeight: FontWeight.bold))),
                  Expanded(
                      child: Text("Return Policy",
                          style: TextStyle(fontWeight: FontWeight.bold))),
                ],
              ),
              Divider(),

              // First Row
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: Text("Size too small, Size too large")),
                  Expanded(child: Text("3 days from delivery")),
                  Expanded(
                      child: Text("Exchange with a different size or colour")),
                ],
              ),
              SizedBox(height: 10),

              // Second Row
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(child: Text("Any other reason")),
                  Expanded(child: Text("10 days from delivery")),
                  Expanded(child: Text("Full refund")),
                ],
              ),
              SizedBox(height: 20),

              // Know More Link
              InkWell(
                onTap: () {
                  // Handle navigation to more details
                },
                child: Text(
                  "Know More",
                  style: TextStyle(
                      color: Colors.blue, fontWeight: FontWeight.bold),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget cartPlace() {
    return Consumer<AddtocartProvider>(builder: (context, provider, child) {
      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 ||
          provider.allitem.items!.isEmpty) {
        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(fontSize: 15)),
              trailing: Icon(
                Icons.arrow_forward_ios,
                size: 15,
              ),
              onTap: () {
                if (provider.couponDataModel.data!.isNotEmpty) {
                  context.push(MyRoutes.COUPONSSCREEN,
                      extra: provider.allitem.id);
                } else {
                  Fluttertoast.showToast(
                    msg: "Coupon's not available !",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.BOTTOM,
                    backgroundColor: Colors.red,
                    textColor: Colors.white,
                    fontSize: 14.0,
                  );
                }
              },
            ),
            Divider(
              thickness: 0.2,
            ),
            SummaryRow(
                label: 'Item Total Price', value: '₹${provider.totalPrice}'),
            SummaryRow(label: 'Discount Price', value: "${provider.discount}"),
            SummaryRow(label: 'Delivery Free', value: 'Free', isGreen: true),
            Divider(
              thickness: 0.2,
            ),
            SummaryRow(
                label: 'Grand Total',
                value: '₹${provider.grandPrice}',
                isBold: true),
            // ListTile(
            //   leading: Container(
            //       decoration: BoxDecoration(
            //           color: Colors.lightGreen.withOpacity(0.2),
            //           borderRadius: BorderRadius.all(Radius.circular(8))),
            //       child: Padding(
            //         padding: const EdgeInsets.all(5.0),
            //         child: Icon(Icons.home_outlined,
            //             size: 15, 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.green)),
            //   onTap: ()
            //    {
            //     _showBottomSheet(context);
            //   },
            // ),
            SizedBox(height: 10),
            Padding(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: Container(
                height: 40,
                decoration: BoxDecoration(
                  color: APPCOLOR.lightGreen,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text("₹${provider.grandPrice}",
                        style: TextStyle(fontSize: 16, color: Colors.white)),
                    Container(
                        width: 1, height: 30, color: APPCOLOR.whiteFBFEFB),
                    InkWell(
                      onTap: () {
                        // if (provider.isDeliverable)
                        // {
                        provider.selectedAddressId();
                        _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(
                        children: [
                          Text('Place Order ',
                              style:
                                  TextStyle(fontSize: 16, color: Colors.white)),
                          Icon(
                            Icons.arrow_forward,
                            color: Colors.white,
                            size: 20,
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          ],
        );
      }
    });
  }

  void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Padding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context)
                  .viewInsets
                  .bottom, // Adjusts for keyboard
            ),
            child: SingleChildScrollView(child: 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: Border.all(color: Colors.grey, width: 1),
                          ),
                          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,
                                      decoration: InputDecoration(
                                        hintText: 'Enter PIN',
                                        counterText: "",
                                        border: InputBorder.none,
                                      ),
                                      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;
                                      },
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 8), // Add some spacing
                                InkWell(
                                  onTap: () {
                                    pinProvider.checkPin(
                                        context, pinProvider.checkPinCode.text);
                                  },
                                  child: pinProvider.ischeckpin
                                      ? Center(
                                          child: CircularProgressIndicator(
                                            color: APPCOLOR.lightGreen,
                                          ),
                                        )
                                      : Text(
                                          "Check PIN",
                                          style: TextStyle(
                                            fontSize: 15,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black,
                                          ),
                                        ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                          height: 10), // Add spacing before the next text
                      if (!pinProvider.isDeliverable)
                        Text(
                          'Delivery is not available for this pincode. Please try another pincode.',
                          style: TextStyle(color: Colors.red, fontSize: 12),
                        )
                      else
                        Text(
                          'Delivery available for this pincode. Submit now.',
                          style:
                              TextStyle(color: Colors.lightGreen, fontSize: 12),
                        ),
                      const SizedBox(
                          height: 10), // Add spacing before the button
                      Center(
                        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();
      },
    );
  }

  Widget bannerview() {
    return Consumer<ProductProvider>(builder: (context, provider, child) {
      return provider.isBannerLoading
          ? Skeletonizer(
              enabled: provider.isBannerLoading,
              child: Container(
                height: 180,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
            )
          : provider.banner.isEmpty
              ? SizedBox.shrink()
              : CarouselSlider(
                  options: CarouselOptions(
                    height: 180,
                    autoPlay: true,
                    enlargeCenterPage: true,
                    viewportFraction: 1,
                    aspectRatio: 16 / 9,
                    initialPage: 0,
                    enableInfiniteScroll: true,
                    reverse: false,
                    autoPlayInterval: Duration(seconds: 3),
                    autoPlayAnimationDuration: Duration(milliseconds: 800),
                    autoPlayCurve: Curves.fastOutSlowIn,
                    enlargeFactor: 0.3,
                  ),
                  items: provider.banner.map((banner) {
                    return Builder(
                      builder: (BuildContext context) {
                        return Container(
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            color: Colors.greenAccent.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(15),
                          ),
                          child: Stack(
                            children: [
                              Positioned(
                                top: 15,
                                left: 15,
                                child: SizedBox(
                                  width: 200,
                                  child: Text(
                                    banner.altText ?? "Special Event",
                                    style: context.customExtraBold(
                                        Colors.black, 18),
                                  ),
                                ),
                              ),
                              Positioned(
                                bottom: 15,
                                left: 15,
                                child: GestureDetector(
                                  onTap: () {
                                    _launchUrl(banner.redirectUrl);
                                  },
                                  child: Container(
                                    height: 40,
                                    width: 100,
                                    decoration: BoxDecoration(
                                      color: APPCOLOR.lightGreen,
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    child: Center(
                                      child: Text(
                                        'Shop now',
                                        style: context.customRegular(
                                            Colors.white, 14),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 15,
                                bottom: 15,
                                child: AppNetworkImage(
                                  height: 130,
                                  width: 150,
                                  imageUrl: banner.imageUrl ??
                                      'https://e7.pngegg.com/pngimages/742/816/png-clipart-coca-cola-can-illustration-coca-cola-soft-drink-surge-pepsi-coke-sweetness-cola-thumbnail.png',
                                  backGroundColor: Colors.transparent,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    );
                  }).toList(),
                );
    });
  }

  Future<void> _launchUrl(url) async {
    print("jdhfjkgh  ${url}");
    final Uri uri = Uri.parse(url);
    if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) {
      throw 'Could not launch $url';
    }
  }
}

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

class _AddressBottomSheetState extends State<AddressBottomSheet> {
  @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),
            Consumer<AddtocartProvider>(
                builder: (context, paymentProvider, child) {
              return ElevatedButton.icon(
                onPressed: () {
                  if (paymentProvider.selectedAddress.isNotEmpty) {
                    if (paymentProvider.isDeliverable) {
                      Navigator.pop(context);
                      Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) {
                          return CardCheckoutScreen(
                            deliveryCharge: paymentProvider.getdeliverycharge,
                            // currency: "INR",
                            originalAmount: paymentProvider.grandPrice,

                            // name: paymentProvider.selecteUserName,
                            // phone: paymentProvider.selecteUserPhone,
                            // email: paymentProvider.selecteEmail,
                            // userId: paymentProvider.allitem.userId!,
                            cartId: paymentProvider.allitem.id!,
                            addressId: paymentProvider.selectedAddress,
                            //  remarks: paymentProvider.selecteUserName,

                            couponId: paymentProvider.couponId,
                          );
                        },
                      ));
                    } else {
                      Fluttertoast.showToast(
                        msg:
                            "Delivery is not available for this address, Please change another address",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 14.0,
                      );
                    }
                  } else {
                    Fluttertoast.showToast(
                      msg: "Please add a delivery address",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      backgroundColor: Colors.green,
                      textColor: Colors.white,
                      fontSize: 14.0,
                    );
                  }
                },
                label: Text(
                  "Continue",
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: paymentProvider.isDeliverable
                      ? Colors.green
                      : Colors.grey,
                  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) {
                  if (addressProvider.selectedAddress.isEmpty) {
                    print("ldjkfhsgkhdfkgkfjgdfjk    ");
                  }
                  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,
                        activeColor: Colors.green,
                        onChanged: (value) {
                          addressProvider.checkAddress(context, value);

                          addressProvider.selectAddress(
                              value.toString(),
                              address.phoneNumber,
                              address.name,
                              address.user!.email);
                        },
                      ),
                      title: Text(
                        address.addressType ?? "",
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      subtitle: Text(address.addressLine +
                              " " +
                              address.landmark +
                              " " +
                              address.city ??
                          ""),
                    ),
                  );
                },
              );
      },
    );
  }

  // void showPaymentMethodBottomSheet(BuildContext context) {
  //   showModalBottomSheet(
  //     context: context,
  //     shape: RoundedRectangleBorder(
  //       borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
  //     ),
  //     builder: (context) {
  //       return Consumer<AddtocartProvider>(
  //         builder: (context, paymentProvider, child) {
  //           return Container(
  //             padding: EdgeInsets.all(16),
  //             height: 250,
  //             child: Column(
  //               crossAxisAlignment: CrossAxisAlignment.start,
  //               children: [
  //                 Text(
  //                   "Select Payment Method",
  //                   style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
  //                 ),
  //                 SizedBox(height: 20),

  //                 // Online Payment Option
  //                 ListTile(
  //                   leading: Icon(Icons.payment, color: Colors.blue),
  //                   title: Text("Online Payment"),
  //                   trailing: paymentProvider.selectedPaymentMethod == "Online"
  //                       ? Icon(Icons.check_circle, color: Colors.green)
  //                       : null,
  //                   onTap: () {
  //                     paymentProvider.selectPaymentMethod("Online");
  //                   },
  //                 ),

  //                 // Cash on Delivery (COD) Option
  //                 ListTile(
  //                   leading: Icon(Icons.money, color: Colors.orange),
  //                   title: Text("Cash on Delivery (COD)"),
  //                   trailing: paymentProvider.selectedPaymentMethod == "COD"
  //                       ? Icon(Icons.check_circle, color: Colors.green)
  //                       : null,
  //                   onTap: () {
  //                     paymentProvider.selectPaymentMethod("COD");
  //                   },
  //                 ),

  //                 ElevatedButton.icon(
  //                   onPressed: () {
  //                     //context.push(MyRoutes.SELECTPAYMENTSCREEN);
  //                     //Navigator.pop(context);
  //                   },
  //                   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)),
  //                   ),
  //                 ),
  //               ],
  //             ),
  //           );
  //         },
  //       );
  //     },
  //   );
  // }
}

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: 14,
                  fontWeight: isBold ? FontWeight.bold : FontWeight.normal)),
          Text(value,
              style: TextStyle(
                  fontSize: 14,
                  fontWeight: isBold ? FontWeight.bold : FontWeight.normal,
                  color: isGreen ? Colors.green : Colors.black)),
        ],
      ),
    );
  }
}
