import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:grocery_app/src/common_widget/network_image.dart';
import 'package:grocery_app/src/core/routes/routes.dart';
import 'package:grocery_app/src/data/ProductCategoryModel.dart';
import 'package:grocery_app/src/data/product_category.dart';

import 'package:grocery_app/src/logic/provider/home_provider.dart';
import 'package:grocery_app/src/ui/data_notfound.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/extensions/uicontext.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';

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

  @override
  State<FruitVeggieDetail> createState() => _FruitVeggieDetailState();
}

class _FruitVeggieDetailState extends State<FruitVeggieDetail> {
  final ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    // Ensuring the context is available before accessing the provider
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final productProvider =
          Provider.of<ProductProvider>(context, listen: false);
      productProvider.getAllcategory(context);
      productProvider.getCategoryByLevel();

      productProvider.gettAllProduct(context, "", true, '');
    });

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        final productProvider =
            Provider.of<ProductProvider>(context, listen: false);
        productProvider.gettAllProduct(context, "", false, '');
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: Center(
          child: SizedBox(
            height: 20,
            width: 20,
            child: InkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: SvgPicture.asset(
                  APPASSETS.back,
                  height: 20,
                  width: 20,
                )),
          ),
        ),
        title: const Text(
          "Vegetables & Fruits",
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w700,
          ),
        ),
        actions: [],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          children: [filterCategory(), productWidget()],
        ),
      ),
    );
  }

  Widget productWidget() {
    return Consumer<ProductProvider>(builder: (context, provider, child) {
      if (provider.isLoadingg) {
        return Padding(
          padding: const EdgeInsets.only(left: 120),
          child: Center(
              child: Container(
            width: 30,
            height: 30,
            decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: APPCOLOR.bgGrey,
                  width: 1,
                )),
            child: const Center(
              child: CupertinoActivityIndicator(),
            ),
          )),
        );
      } else if (provider.products.isEmpty) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.only(left: 40),
            child: DataNotFound(
              imagePath: 'assets/images/cart.jpg',
              message: "Product not abailable   ",
              width: 220.w,
              height: 250.h,
            ),
          ),
        );
      } else {
        return Expanded(
          child: Padding(
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: LayoutBuilder(
              builder: (context, constraints) {
                final itemWidth = (constraints.maxWidth - 20) / 2;
                final itemHeight = itemWidth * 1.5;

                return GridView.builder(
                  controller: _scrollController,
                  // itemCount: provider.products.length,

                  itemCount:
                      provider.products.length + (provider.hasMore ? 1 : 0),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: itemWidth / itemHeight,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                  ),
                  itemBuilder: (context, index) {
                    if (index == provider.products.length) {
                      return SizedBox.shrink();
                      // return Center(
                      //     child: Padding(
                      //   padding: const EdgeInsets.only(left: 120),
                      //   child: Center(
                      //       child: Container(
                      //     width: 30,
                      //     height: 30,
                      //     decoration: BoxDecoration(
                      //         color: Colors.transparent,
                      //         borderRadius: BorderRadius.circular(20),
                      //         border: Border.all(
                      //           color: APPCOLOR.bgGrey,
                      //           width: 1,
                      //         )),
                      //     child: const Center(
                      //       child: CupertinoActivityIndicator(),
                      //     ),
                      //   )),
                      // )
                      // ); // Show loader when fetching more data
                    }
                    var product = provider.products[index];
                    return InkWell(
                      onTap: () {
                        context.push(
                          MyRoutes.PRODUCTDETAILS,
                          // extra: product.id

                          extra: {
                            "id": product.id,
                            "quantity": 1,
                            "price": product.discountPrice,
                          },
                        );
                      },
                      child: Container(
                        height: itemHeight,
                        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: itemWidth *
                                    0.6, // Adjust height for image container
                                width: itemWidth,
                                decoration: BoxDecoration(
                                  color: APPCOLOR.bgGrey,
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                child: Stack(
                                  alignment: Alignment.center,
                                  children: [
                                    AppNetworkImage(
                                      height: 70,
                                      width: 150,
                                      imageUrl: product
                                              .productImages!.first.url ??
                                          "https://5.imimg.com/data5/SELLER/Default/2024/2/385126988/OL/DA/VW/8627346/1l-fortune-sunflower-oil.jpg",
                                      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(product.basePrice), double.parse(product!.discountPrice))}% OFF",
                                              style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 12)),
                                        ),
                                      ),
                                    )
                                    // Positioned(
                                    //   right: 5,
                                    //   top: 5,
                                    //   child: InkWell(
                                    //     onTap: () async {
                                    //       if (await SharedPrefUtils.getToken() !=
                                    //           null) {
                                    //         if (product.isInWishlist) {
                                    //           Fluttertoast.showToast(
                                    //             msg: "Item already added!",
                                    //             toastLength: Toast.LENGTH_SHORT,
                                    //             gravity: ToastGravity.BOTTOM,
                                    //             backgroundColor: Colors.green,
                                    //             textColor: Colors.white,
                                    //             fontSize: 14.0,
                                    //           );
                                    //         } else {
                                    //           //product.isInWishlist=ture;
                                    //           provider
                                    //               .toggleWishlist1(product.id!);
                                    //         }
                                    //       } else {
                                    //         context.push(MyRoutes.LOGIN);
                                    //       }
                                    //     },
                                    //     child: Icon(
                                    //       product.isInWishlist
                                    //           ? Icons.favorite
                                    //           : Icons.favorite_border,
                                    //       color: product.isInWishlist
                                    //           ? Colors.red
                                    //           : Colors.grey,
                                    //     ),
                                    //   ),
                                    // ),

                                    // Positioned(
                                    //   right: 5,
                                    //   top: 5,
                                    //   child: InkWell(
                                    //     onTap: () async {
                                    //       if (await SharedPrefUtils
                                    //               .getToken() !=
                                    //           null) {
                                    //         provider.toggleWishlist(
                                    //             context, product.id!);
                                    //       } else {
                                    //         context.push(MyRoutes.SIGNUP);
                                    //       }
                                    //     },
                                    //     child: Icon(
                                    //       provider.wishlist.contains(product.id)
                                    //           ? Icons.favorite
                                    //           : Icons.favorite_border,
                                    //       color: provider.wishlist
                                    //               .contains(product.id)
                                    //           ? Colors.red
                                    //           : Colors.grey,
                                    //     ),
                                    //   ),
                                    // ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 5),
                              Text(
                                product.name ?? " ",
                                textAlign: TextAlign.left,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: context
                                    .customMedium(
                                      APPCOLOR.balck1A1A1A,
                                      15,
                                    )
                                    .copyWith(fontWeight: FontWeight.bold),
                              ),
                              const SizedBox(height: 2),
                              Text(
                                product.unit ?? " ",
                                textAlign: TextAlign.left,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: context.customMedium(
                                  Colors.grey.withOpacity(0.8),
                                  13,
                                ),
                              ),
                              const SizedBox(height: 1),
                              Spacer(),
                              Row(
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        "₹${product.discountPrice ?? " "}",
                                        textAlign: TextAlign.left,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: context.customSemiBold(
                                            Colors.black, 16),
                                      ),
                                      const SizedBox(width: 5),
                                      Text(
                                        "₹${product.basePrice ?? " "}",
                                        textAlign: TextAlign.left,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: context
                                            .customMedium(
                                              Colors.grey.withOpacity(0.8),
                                              16,
                                            )
                                            .copyWith(
                                              decoration:
                                                  TextDecoration.lineThrough,
                                            ),
                                      ),
                                    ],
                                  ),
                                  Spacer(),
                                  Align(
                                    alignment: Alignment.centerRight,
                                    child: GestureDetector(
                                      onTap: () async {
                                        print(
                                            "Add to Cart Pressed for ${product.id}");

                                        if (await SharedPrefUtils.getToken() !=
                                            null) {
                                          await provider.addToCart(
                                              context, product.id!, 1);
                                        } else {
                                          context.push(MyRoutes.SIGNUP);
                                        }
                                      },
                                      child: Container(
                                        height:
                                            MediaQuery.of(context).size.height *
                                                0.038,
                                        width:
                                            MediaQuery.of(context).size.width *
                                                0.1,
                                        decoration: BoxDecoration(
                                          color: APPCOLOR.lightGreen,
                                          borderRadius:
                                              BorderRadius.circular(5),
                                        ),
                                        child: Center(
                                          child: provider
                                                      .isLoading[product.id] ??
                                                  false
                                              ? Padding(
                                                  padding:
                                                      const EdgeInsets.all(8.0),
                                                  child: Container(
                                                    height: 10,
                                                    width: 10,
                                                    child:
                                                        CircularProgressIndicator(
                                                            color: Colors.white,
                                                            strokeWidth: 2),
                                                  ),
                                                )
                                              : Text(
                                                  // provider.cartItems
                                                  //         .contains(bestdealproduct.id)
                                                  //     ? 'Added'
                                                  //     :
                                                  '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;

    return discountPercentage.round();
  }

  Widget filterCategory() {
    final activeIndexProvider = Provider.of<ProductProvider>(context);

    return Consumer<ProductProvider>(builder: (context, provider, child) {
      if (provider.iscategroyloading) {
        return Center(
          child: Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
              color: APPCOLOR.bgGrey,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: APPCOLOR.bgGrey,
                width: 1,
              ),
            ),
            child: const Center(
              child: CupertinoActivityIndicator(),
            ),
          ),
        );
      } else {
        final categories = [DatumCategory(id: "all", name: "ALL")];
        categories.addAll(provider.categoryList.cast<DatumCategory>());

        return Container(
          decoration: const BoxDecoration(color: Colors.white),
          width: 70,
          child: ListView.builder(
            itemCount: categories.length,
            scrollDirection: Axis.vertical,
            itemBuilder: (context, index) {
              var category = categories[index];

              return Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: InkWell(
                  onTap: () {
                    provider.iscroll = true;
                    provider.products.clear();
                    provider.isLoadingg = false;
                    provider.hasMore = true;
                    provider.page = 1;
                    provider.notifyListeners();

                    if (category.id == "all") {
                      provider.gettAllProduct(context, "", true, '');
                    } else {
                      // Load filtered products
                      provider.gettAllProduct(
                          context, "/category/${category.id}", true, '');
                    }

                    activeIndexProvider.setActiveIndex(index);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        color: activeIndexProvider.activeIndex == index
                            ? Colors.greenAccent.withOpacity(0.3)
                            : APPCOLOR.bgGrey,
                        borderRadius: BorderRadius.circular(5)),
                    child: Padding(
                      padding: const EdgeInsets.only(top: 10, bottom: 10),
                      child: SizedBox(
                        //  height: 80,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            if (category.name == "ALL") ...{
                              if (provider.categoriesss.isNotEmpty)
                                PopupMenuButton<ProductCategoryModel>(
                                  onSelected: (ProductCategoryModel value) {
                                    activeIndexProvider.setActiveIndex(0);

                                    if (value.id == "all") {
                                      provider.iscroll = true;
                                      provider.products.clear();
                                      provider.isLoadingg = false;
                                      provider.hasMore = true;
                                      provider.page = 1;
                                      provider.gettAllProduct(
                                          context, "", true, '');
                                      provider.getAllcategory(context);
                                    } else {
                                      provider.categoryList.clear();
                                      provider.getSubcategory(
                                          context, value.id);
                                    }

                                    provider.setSelectedCategory(value);
                                  },
                                  itemBuilder: (BuildContext context) =>
                                      provider.categoriesss
                                          .map(
                                            (category) => PopupMenuItem(
                                              value: category,
                                              child: Text(
                                                  category.name ?? "Unknown"),
                                            ),
                                          )
                                          .toList(),
                                  child: Center(
                                    child: Container(
                                      child: AppNetworkImage(
                                        height: 50,
                                        width: 60,
                                        imageUrl: provider
                                                .selectedCategory?.image ??
                                            'https://i.pinimg.com/originals/a5/f3/5f/a5f35fb23e942809da3df91b23718e8d.png',
                                        backGroundColor: APPCOLOR.bgGrey,
                                        radius: 10,
                                      ),
                                    ),
                                  ),
                                ),
                            } else ...{
                              Column(
                                children: [
                                  Center(
                                    child: Container(
                                      child: AppNetworkImage(
                                        height: 50,
                                        width: 50,
                                        imageUrl: category.image ??
                                            'https://i.pinimg.com/originals/a5/f3/5f/a5f35fb23e942809da3df91b23718e8d.png',
                                        backGroundColor: APPCOLOR.bgGrey,
                                        radius: 10,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 5,
                                  ),
                                  Container(
                                    width: 50,
                                    child: Text(
                                      category.name,
                                      textAlign: TextAlign.center,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: activeIndexProvider.activeIndex ==
                                              index
                                          ? context.customExtraBold(
                                              APPCOLOR.balck1A1A1A, 9)
                                          : context.customMedium(
                                              APPCOLOR.balck1A1A1A, 10),
                                    ),
                                  ),
                                ],
                              ),
                            },
                            // SizedBox(
                            //   width: 5,
                            // ),
                            // Container(
                            //   width: 2,
                            //    height: 0,
                            //   color: activeIndexProvider.activeIndex == index
                            //       ? APPCOLOR.lightGreen
                            //       : Colors.transparent,
                            // ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      }
    });
  }
}
