import 'dart:async';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_rating_stars/flutter_rating_stars.dart';
import 'package:flutter_svg/svg.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/core/routes/routes.dart';

import 'package:grocery_app/src/data/product_details.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/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:intl/intl.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:readmore/readmore.dart';
import 'package:shimmer/shimmer.dart';

class ProductDetails extends StatefulWidget {
  String id;
  int quantity;
  String price;

  ProductDetails(
      {super.key,
      required this.id,
      required this.quantity,
      required this.price});

  @override
  State<ProductDetails> createState() => _ProductDetailsState();
}

class _ProductDetailsState extends State<ProductDetails> {
  int quantity = 1;
  int selectedImage = 0;

  String productId = '';
  @override
  void initState() {
    super.initState();
    Provider.of<ProductProvider>(context, listen: false)
        .getProduuctDetails(context, widget.id, widget.quantity, widget.price);
  }

  double value = 3.5;

  bool isExpanded = false;
  bool isHilightsExpanded = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        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(
          "Item Details",
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w700,
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              prodectDtails(),
              Divider(),
              reviews(),
              Gap(5),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Text("Similar Products",
                    style:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
              ),
              bestDeal(),
              SizedBox(
                height: 100,
              )
            ],
          ),
        ),
      ),
      bottomNavigationBar: bottomBar(),
    );
  }

  int calculateDiscountPercentage(double basePrice, double discountPrice) {
    if (basePrice <= 0 || discountPrice <= 0 || discountPrice > basePrice) {
      return 0;
    }

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

    return discountPercentage.round();
  }

  Widget prodectDtails() {
    return Consumer<ProductProvider>(builder: (context, provider, child) {
      if (provider.isProductLoading) {
        return _buildSkeletonLoader();
      } else if (provider.productDetails.data == null) {
        return Center(child: Text('No products available'));
      } else {
        provider.setProductPrice(
            double.parse(provider.productDetails.data!.discountPrice));
        provider.productQuantity = provider.productDetails.data!.quantity;

        if (provider.productDetails.data!.isInWishlist!) {
          provider.wishlist.contains(provider.productDetails.data!.id);
        }
        return Column(
          children: [
            SizedBox(
              height: 300,
              child: CarouselSlider.builder(
                itemCount:
                    provider.productDetails.data!.productImages!.length ?? 0,
                itemBuilder: (context, index, realIndex) {
                  var productImage =
                      provider.productDetails.data!.productImages![index];
                  return AppNetworkImage(
                    height: MediaQuery.of(context).size.height * 0.08,
                    width: 2000,
                    imageUrl: productImage.url,
                    backGroundColor: Colors.transparent,
                  );

                  // Image.network(productImage.url ??
                  //     'https://i.pinimg.com/originals/a5/f3/5f/a5f35fb23e942809da3df91b23718e8d.png');
                },
                options: CarouselOptions(
                  height: 300,
                  initialPage: selectedImage,
                  enableInfiniteScroll: true,
                  autoPlay: true,
                  autoPlayInterval: Duration(seconds: 3),
                  autoPlayAnimationDuration: Duration(milliseconds: 800),
                  enlargeCenterPage: true,
                  onPageChanged: (index, reason) {
                    setState(() {
                      selectedImage = index;
                    });
                  },
                ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: provider.productDetails.data!.productImages!.map((url) {
                int index =
                    provider.productDetails.data!.productImages!.indexOf(url);
                return Container(
                  margin: EdgeInsets.symmetric(horizontal: 5),
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: selectedImage == index ? Colors.red : Colors.grey,
                  ),
                );
              }).toList(),
            ),
            SizedBox(height: 10),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 1.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          provider.productDetails.data!.name ?? "",
                          style: context.customExtraBold(Colors.black, 18),
                        ),
                        Gap(5),
                        Row(
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.green,
                                borderRadius: BorderRadius.circular(5),
                              ),
                              child: Row(
                                children: [
                                  Icon(
                                    Icons.star,
                                    size: 20,
                                    color: Colors.white,
                                  ),
                                  Text(
                                      provider.productDetails.data!
                                              .averageRating ??
                                          "0.0",
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 14)),
                                ],
                              ),
                            ),
                            Text(
                                " (${provider.productDetails.data!.productReview!.length + 1} Review)",
                                style: TextStyle(
                                    color: Colors.black, fontSize: 14)),
                            Spacer(),
                            if (provider.productDetails.data!.stock > 0) ...{
                              Text("In Stock",
                                  style: TextStyle(
                                      color: Colors.green, fontSize: 14)),
                            } else ...{
                              Text("Out Of Stock",
                                  style: TextStyle(
                                      color: Colors.red, fontSize: 14)),
                            }
                          ],
                        ),
                        Gap(5),
                        Row(
                          children: [
                            Text(
                              "₹${provider.productDetails.data!.discountPrice}",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.green),
                            ),
                            SizedBox(width: 10),
                            Text(
                              "₹${provider.productDetails.data!.basePrice}",
                              style: TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                decoration: TextDecoration.lineThrough,
                                color: Colors.grey,
                              ),
                            ),
                            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(provider.productDetails.data!.basePrice), double.parse(provider.productDetails.data!.discountPrice))}% OFF",
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 14)),
                            ),
                            Spacer(),
                            InkWell(
                              onTap: () async {
                                if (await SharedPrefUtils.getToken() != null) {
                                  provider.toggleWishlist(context,
                                      provider.productDetails.data!.id!);
                                } else {
                                  context.push(MyRoutes.SIGNUP);
                                }
                              },
                              child: provider.iswishloading
                                  ? Container(
                                      width: 10,
                                      height: 10,
                                      child: CircularProgressIndicator(
                                        color: Colors.green,
                                        strokeWidth: 1,
                                      ),
                                    )
                                  : Icon(
                                      provider.wishlist.contains(
                                              provider.productDetails.data!.id)
                                          ? Icons.favorite
                                          : Icons.favorite_border,
                                      color: provider.wishlist.contains(
                                              provider.productDetails.data!.id)
                                          ? Colors.red
                                          : Colors.grey,
                                    ),
                            ),
                          ],
                        ),
                        Gap(5),
                        ReadMoreText(
                          provider.productDetails.data!.description ?? "",
                          trimMode: TrimMode.Line,
                          trimLines: 2,
                          colorClickableText: APPCOLOR.appGreen,
                          trimCollapsedText: 'Read More',
                          trimExpandedText: 'Show less',
                          style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
                        ),
                        Gap(5),
                        InkWell(
                          onTap: () {
                            showReturnPolicyBottomSheet(context);
                          },
                          child: Text("3 days Return & Exchange ",
                              style:
                                  TextStyle(color: Colors.green, fontSize: 14)),
                        ),
                      ],
                    ),
                  ),
                  Gap(5),
                  Card(
                    elevation: 5,
                    color: Colors.white,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if (provider.productDetails.data!.productHighlight!
                              .isNotEmpty) ...{
                            Row(
                              children: [
                                Text("Highlights",
                                    style: TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold)),
                                Gap(2),
                                Expanded(
                                  child: Container(
                                    color: Colors.grey,
                                    height: 0.4,
                                  ),
                                )
                              ],
                            ),
                            if (provider.productDetails.data!.productHighlight!
                                .isNotEmpty)
                              AnimatedSize(
                                duration: Duration(milliseconds: 300),
                                curve: Curves.easeInOut,
                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: ListView.builder(
                                    shrinkWrap: true,
                                    physics: NeverScrollableScrollPhysics(),
                                    itemCount: isHilightsExpanded
                                        ? provider.productDetails.data!
                                            .productHighlight!.length
                                        : 1,
                                    itemBuilder: (context, index) {
                                      final item = provider.productDetails.data!
                                          .productHighlight![index];
                                      return _buildText(
                                          item.key ?? '', item.value ?? '');
                                    },
                                  ),
                                ),
                              ),
                            Center(
                              child: TextButton(
                                onPressed: () {
                                  setState(() {
                                    isHilightsExpanded = !isHilightsExpanded;
                                  });
                                },
                                child: Text(
                                  isHilightsExpanded
                                      ? "View Less"
                                      : "View More",
                                  style: TextStyle(color: APPCOLOR.appGreen),
                                ),
                              ),
                            ),
                          },

                          Row(
                            children: [
                              Text("Information",
                                  style: TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold)),
                              Gap(2),
                              Expanded(
                                child: Container(
                                  color: Colors.grey,
                                  height: 0.4,
                                ),
                              )
                            ],
                          ),
                          AnimatedSize(
                            duration: Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                children: [
                                  _buildText(
                                    "Customer Care Details ",
                                    'In case of any issue, contact us${provider.productDetails.data!.store!.officialPhoneNumber ?? ''}',
                                  ),
                                  if (isExpanded)
                                    _buildText(
                                      "Seller Name ",
                                      '${provider.productDetails.data!.store!.storeName ?? ""}',
                                    ),
                                  if (isExpanded)
                                    _buildText(
                                      "Seller Address",
                                      '${provider.productDetails.data!.store!.storeAddress ?? ""}',
                                    ),
                                  // if (isExpanded)
                                  //   _buildText(
                                  //     "GST Number",
                                  //     '${provider.productDetails.data!.store!.gstNumber ?? ""}',

                                  //   ),
                                ],
                              ),
                            ),
                          ),
                          // Padding(
                          //   padding: const EdgeInsets.symmetric(vertical: 4.0),
                          //   child: Column(
                          //     children: [
                          //       _buildText("Customer Care Details ",
                          //           'In case of any issue, contact us${provider.productDetails.data!.store!.officialPhoneNumber ?? ''}'),
                          //       _buildText("Seller Name ",
                          //           '${provider.productDetails.data!.store!.storeName ?? ""}'),
                          //       _buildText("Seller Address",
                          //           '${provider.productDetails.data!.store!.storeAddress ?? ""}'),
                          //       _buildText("GST Number",
                          //           '${provider.productDetails.data!.store!.gstNumber ?? ""}'),
                          //     ],
                          //   ),
                          // ),

                          Center(
                            child: TextButton(
                              onPressed: () {
                                setState(() {
                                  isExpanded = !isExpanded;
                                });
                              },
                              child: Text(
                                isExpanded ? "View Less" : "View More",
                                style: TextStyle(color: APPCOLOR.appGreen),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
      }
    });
  }

  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 _buildText(String title, String value) {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: Text(
              title,
              style: TextStyle(fontSize: 12),
            ),
          ),
          Expanded(
            flex: 4,
            child: Text(
              value,
              style: TextStyle(fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSkeletonLoader() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[100]!,
            child: Container(
              height: 300,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 10),
          Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[100]!,
            child: Container(
              height: 20,
              width: double.infinity,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 10),
          Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[100]!,
            child: Container(
              height: 20,
              width: 150,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  Widget reviews() {
    return Consumer<ProductProvider>(builder: (context, provider, child) {
      if (provider.isProductLoading) {
        return SizedBox.shrink();
      } else if (provider.productDetails.data == null) {
        return Center(child: Text('No products available'));
      } else {
        return provider.productDetails.data!.productReview!.isNotEmpty
            ? Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Reviews & Ratings",
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold)),
                    SizedBox(height: 10),
                    Row(
                      children: [
                        Text(provider.productDetails.data!.averageRating ?? "",
                            style: TextStyle(
                                fontSize: 30, fontWeight: FontWeight.bold)),
                        SizedBox(
                          width: 10,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            RatingStars(
                              value:
                                  provider.productDetails.data!.averageRating ??
                                      0,
                              onValueChanged: (v) {
                                //
                                setState(() {
                                  value = v;
                                });
                              },
                              starBuilder: (index, color) => Icon(
                                Icons.star,
                                color: color,
                              ),
                              starCount: 5,
                              starSize: 20,
                              valueLabelColor: const Color(0xff9b9b9b),
                              valueLabelTextStyle: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w400,
                                  fontStyle: FontStyle.normal,
                                  fontSize: 12.0),
                              valueLabelRadius: 10,
                              maxValue: 5,
                              starSpacing: 2,
                              maxValueVisibility: false,
                              valueLabelVisibility: false,
                              animationDuration: Duration(milliseconds: 1000),
                              valueLabelPadding: const EdgeInsets.symmetric(
                                  vertical: 1, horizontal: 8),
                              valueLabelMargin: const EdgeInsets.only(right: 8),
                              starOffColor: const Color(0xffe7e8ea),
                              starColor: Colors.green,
                            ),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    Row(
                      crossAxisAlignment:
                          CrossAxisAlignment.start, // Align items at the top
                      children: [
                        CircleAvatar(
                          backgroundImage:
                              NetworkImage('https://via.placeholder.com/50'),
                        ),
                        SizedBox(width: 10),

                        // Column for Text and RatingStars
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment
                                    .spaceBetween, // Proper spacing
                                children: [
                                  Text(
                                    provider.productDetails.data!.productReview!
                                            .first.user!.firstName +
                                        " " +
                                        provider
                                            .productDetails
                                            .data!
                                            .productReview!
                                            .first
                                            .user!
                                            .lastName,
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  RatingStars(
                                    value: double.parse(provider
                                            .productDetails
                                            .data!
                                            .productReview!
                                            .first
                                            .rating ??
                                        0),
                                    starBuilder: (index, color) => Icon(
                                      Icons.star,
                                      color: color,
                                    ),
                                    starCount: 5,
                                    starSize: 20,
                                    maxValue: 5,
                                    starSpacing: 2,
                                    maxValueVisibility: false,
                                    valueLabelVisibility: false,
                                    animationDuration:
                                        Duration(milliseconds: 1000),
                                    valueLabelPadding:
                                        const EdgeInsets.symmetric(
                                            vertical: 1, horizontal: 8),
                                    valueLabelMargin:
                                        const EdgeInsets.only(right: 8),
                                    starOffColor: const Color(0xffe7e8ea),
                                    starColor: Colors.green,
                                  ),
                                ],
                              ),
                              SizedBox(height: 4),
                              Text(
                                formatDate(provider.productDetails.data!
                                    .productReview!.first.createdAt
                                    .toString()),
                                style: TextStyle(color: Colors.grey),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    ReadMoreText(
                      "${provider.productDetails.data!.productReview!.first.title ?? ""}" +
                          "\n" +
                          "${provider.productDetails.data!.productReview!.first.description ?? ""}",
                      trimMode: TrimMode.Line,
                      trimLines: 2,
                      colorClickableText: APPCOLOR.appGreen,
                      trimCollapsedText: 'Read More',
                      trimExpandedText: 'Show less',
                      style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
                    ),
                    if (provider.productDetails.data!.productReview!.first
                        .productReviewImage!.isNotEmpty)
                      reviewImage(provider.productDetails.data!.productReview!
                          .first.productReviewImage)
                  ],
                ),
              )
            : Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("Reviews & Ratings",
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold)),
                    SizedBox(height: 10),
                    Row(
                      children: [
                        Text("4.2",
                            style: TextStyle(
                                fontSize: 30, fontWeight: FontWeight.bold)),
                        SizedBox(
                          width: 10,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            RatingStars(
                              value: value,
                              onValueChanged: (v) {
                                //
                              },
                              starBuilder: (index, color) => Icon(
                                Icons.star,
                                color: color,
                              ),
                              starCount: 5,
                              starSize: 20,
                              valueLabelColor: const Color(0xff9b9b9b),
                              valueLabelTextStyle: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w400,
                                  fontStyle: FontStyle.normal,
                                  fontSize: 12.0),
                              valueLabelRadius: 10,
                              maxValue: 5,
                              starSpacing: 2,
                              maxValueVisibility: false,
                              valueLabelVisibility: false,
                              animationDuration: Duration(milliseconds: 1000),
                              valueLabelPadding: const EdgeInsets.symmetric(
                                  vertical: 1, horizontal: 8),
                              valueLabelMargin: const EdgeInsets.only(right: 8),
                              starOffColor: const Color(0xffe7e8ea),
                              starColor: Colors.green,
                            ),
                            Text(
                              "April 10, 2023",
                              style: TextStyle(color: Colors.grey),
                            ),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    Row(
                      crossAxisAlignment:
                          CrossAxisAlignment.start, // Align items at the top
                      children: [
                        CircleAvatar(
                          backgroundImage:
                              NetworkImage('https://via.placeholder.com/50'),
                        ),
                        SizedBox(width: 10),

                        // Column for Text and RatingStars
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment
                                    .spaceBetween, // Proper spacing
                                children: [
                                  Text(
                                    "Johnson Smith",
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  RatingStars(
                                    value: value,
                                    starBuilder: (index, color) => Icon(
                                      Icons.star,
                                      color: color,
                                    ),
                                    starCount: 5,
                                    starSize: 20,
                                    maxValue: 5,
                                    starSpacing: 2,
                                    maxValueVisibility: false,
                                    valueLabelVisibility: false,
                                    animationDuration:
                                        Duration(milliseconds: 1000),
                                    valueLabelPadding:
                                        const EdgeInsets.symmetric(
                                            vertical: 1, horizontal: 8),
                                    valueLabelMargin:
                                        const EdgeInsets.only(right: 8),
                                    starOffColor: const Color(0xffe7e8ea),
                                    starColor: Colors.green,
                                  ),
                                ],
                              ),
                              SizedBox(height: 4),
                              Text(
                                "April 10, 2023",
                                style: TextStyle(color: Colors.grey),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    ReadMoreText(
                      'Flutter is Google’s mobile UI open source framework to build high-quality native (super fast) interfaces for iOS and Android apps with the unified codebase.',
                      trimMode: TrimMode.Line,
                      trimLines: 2,
                      colorClickableText: APPCOLOR.appGreen,
                      trimCollapsedText: 'Read More',
                      trimExpandedText: 'Show less',
                      style: context.customMedium(APPCOLOR.balck1A1A1A, 14),
                    ),
                  ],
                ),
              );
      }
    });
  }

  Widget reviewImage(List<ProductReviewImage>? productReviewImage) {
    return SizedBox(
      height: 100,
      child: ListView.builder(
        itemCount: 10,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return InkWell(
            onTap: () {},
            child: Center(
              child: Container(
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                  color: APPCOLOR.bgGrey,
                  borderRadius: BorderRadius.circular(15),
                ),
                child: AppNetworkImage(
                  height: 90,
                  width: 90,
                  imageUrl: "",
                  backGroundColor: Colors.transparent,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  String formatDate(String dateStr) {
    // Parse the date string to DateTime
    DateTime date = DateTime.parse(dateStr).toLocal();

    // Format the date
    return DateFormat('MMMM d, yyyy').format(date); // "February 4, 2025"
  }

  Widget bestDeal() {
    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: () {
                  provider.getProduuctDetails(
                      context, bestdealproduct.id, 0, "0");
                },
                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,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          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,
                                        ),
                                  ),
                                ],
                              ),

                              // Align(
                              //   alignment: Alignment.centerRight,
                              //   child: InkWell(
                              //     onTap: () async {
                              //       bool success = await provider.addToCart(context, bestdealproduct.id!);
                              //     if (success) {
                              //       Fluttertoast.showToast(
                              //         msg: "Product added to cart!",
                              //         toastLength: Toast.LENGTH_SHORT,
                              //         gravity: ToastGravity.BOTTOM,
                              //         backgroundColor: Colors.green,
                              //         textColor: Colors.white,
                              //         fontSize: 14.0,
                              //       );
                              //     }

                              //     },
                              //     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: Text(
                              //           'Add',
                              //           style:
                              //               context.customRegular(Colors.white, 12),
                              //         ),
                              //       ),
                              //     ),
                              //   ),
                              // ),
                              const Spacer(),
                              Align(
                                alignment: Alignment.centerRight,
                                child: GestureDetector(
                                  onTap: () async {
                                    if (await SharedPrefUtils.getToken() !=
                                        null) {
                                      provider.isLoading[bestdealproduct.id] ??
                                              false
                                          ? null
                                          : () => provider.addToCart(
                                              context, bestdealproduct.id!, 1);
                                    } 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: provider.cartItems
                                              .contains(bestdealproduct.id)
                                          ? Colors.grey
                                          : APPCOLOR.lightGreen,
                                      borderRadius: BorderRadius.circular(5),
                                    ),
                                    child: Center(
                                      child: provider.isLoading[
                                                  bestdealproduct.id] ??
                                              false
                                          ? CircularProgressIndicator(
                                              color: Colors.white,
                                              strokeWidth: 2)
                                          : Text(
                                              provider.cartItems.contains(
                                                      bestdealproduct.id)
                                                  ? 'Added'
                                                  : 'Add',
                                              style: context.customRegular(
                                                  Colors.white, 12),
                                            ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      }
    });
  }

  Widget bottomBar() {
    return Consumer<ProductProvider>(builder: (context, cartProvider, child) {
      return Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [BoxShadow(color: Colors.grey.shade300, blurRadius: 10)],
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                IconButton(
                  icon: Icon(Icons.remove_circle_outline),
                  onPressed: cartProvider.decreaseQuantity,
                ),
                Text("${cartProvider.quantity}",
                    style:
                        TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                IconButton(
                  icon: Icon(Icons.add_circle_outline),
                  onPressed: cartProvider.increaseQuantity,
                ),
              ],
            ),
            Container(
              height: 50,
              decoration: BoxDecoration(
                color: APPCOLOR.lightGreen,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: Row(
                    children: [
                      InkWell(
                        onTap: () async {
                          if (await SharedPrefUtils.getToken() != null) {
                            cartProvider.addToCart(
                                context,
                                cartProvider.productDetails.data!.id!,
                                cartProvider.quantity);
                          } else {
                            context.push(MyRoutes.SIGNUP);
                          }
                        },
                        child: cartProvider.isLoadingCart
                            ? Padding(
                                padding:
                                    const EdgeInsets.only(left: 40, right: 40),
                                child: Container(
                                  height: 15,
                                  width: 15,
                                  child: Center(
                                    child: CircularProgressIndicator(
                                        color: Colors.white, strokeWidth: 2),
                                  ),
                                ),
                              )
                            : Text(
                                'Add to Cart',
                                style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white),
                              ),
                      ),
                      SizedBox(width: 10),
                      Container(
                          width: 2, height: 50, color: APPCOLOR.whiteFBFEFB),
                      SizedBox(width: 10),
                      Text(
                        "₹${cartProvider.totalPrice}",
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      );
    });
  }
}

//   Widget _slider(BuildContext context) {
//   double height = MediaQuery.of(context).size.height * .43;
//   double statusBarHeight = MediaQuery.of(context).padding.top;

//   // Fetch product data from Provider
//   final productProvider = Provider.of<ProductProvider>(context);
//   Product? model = productProvider.selectedProduct; // Ensure you have a selected product

//   if (model == null) {
//     return Center(child: CircularProgressIndicator()); // Show loading if no product data
//   }

//   return GestureDetector(
//     onTap: () {
//       Navigator.push(
//         context,
//         PageRouteBuilder(
//           pageBuilder: (_, __, ___) => ProductPreview(
//             pos: _curSlider,
//             secPos: widget.secPos,
//             index: widget.index,
//             id: model.id,
//             imgList: sliderList,
//             list: widget.list,
//             video: model.video,
//             videoType: model.videType,
//             from: true,
//           ),
//         ),
//       );
//     },
//     child: Stack(
//       children: <Widget>[
//         Container(
//           alignment: Alignment.center,
//           padding: EdgeInsets.only(top: statusBarHeight + kToolbarHeight),
//           child: PageView.builder(
//             physics: const BouncingScrollPhysics(),
//             itemCount: sliderList.length,
//             scrollDirection: Axis.horizontal,
//             controller: _pageController,
//             reverse: false,
//             onPageChanged: (index) {
//               setState(() {
//                 _curSlider = index;
//               });
//             },
//             itemBuilder: (BuildContext context, int i) {
//               return sliderList[i] != "youtube"
//                   ? networkImageCommon(sliderList[i]!, height, true)
//                   : playIcon(model);
//             },
//           ),
//         ),
//         Positioned(
//           bottom: 30,
//           height: 20,
//           width: MediaQuery.of(context).size.width,
//           child: Row(
//             mainAxisSize: MainAxisSize.max,
//             mainAxisAlignment: MainAxisAlignment.center,
//             children: List.generate(
//               sliderList.length,
//               (index) => AnimatedContainer(
//                 duration: const Duration(milliseconds: 500),
//                 width: _curSlider == index ? 30.0 : 8.0,
//                 height: 8.0,
//                 margin: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 4.0),
//                 decoration: BoxDecoration(
//                   border: Border.all(
//                       color: Theme.of(context).colorScheme.primary),
//                   borderRadius: BorderRadius.circular(20.0),
//                   color: _curSlider == index
//                       ? Theme.of(context).colorScheme.primary
//                       : Colors.transparent,
//                 ),
//               ),
//             ),
//           ),
//         ),
//         indicatorImage(model),
//       ],
//     ),
//   );
// }
