import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/enums/review_display_policy.dart';
import 'package:niogu_ecommerce_v1/core/enums/review_display_type.dart';
import 'package:niogu_ecommerce_v1/core/enums/stock_type.dart';
import 'package:niogu_ecommerce_v1/core/providers/app_provider.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/system/system_setting.dart';
import 'package:niogu_ecommerce_v1/core/utils/currency_format.dart';
import 'package:niogu_ecommerce_v1/core/utils/extenstion_format.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.dart';
import 'package:niogu_ecommerce_v1/features/account/presentation/widgets/login_auth_modal.dart';
import 'package:niogu_ecommerce_v1/features/cart/domain/entities/cart.dart';
import 'package:niogu_ecommerce_v1/features/cart/presentation/providers/cart_provider.dart';
import 'package:niogu_ecommerce_v1/features/product/domain/entities/product.dart';
import 'package:sizer/sizer.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';

class ProductDetailScreen extends ConsumerStatefulWidget {
  final ProductDetail productDetail;
  const ProductDetailScreen({super.key, required this.productDetail});

  @override
  ConsumerState<ProductDetailScreen> createState() =>
      _ProductDetailScreenState();
}

class _ProductDetailScreenState extends ConsumerState<ProductDetailScreen> {
  final PageController _imageController = PageController();

  late final ProductDetail _productDetail;

  late final ReviewDisplayType _displayType;

  late final ReviewDisplayPolicy _displayPolicy;

  late final ProductInfo _productInfo;

  final List<String> _productImages = [];

  final List<ProductVariant> _variants = [];

  final List<ProductReview> _reviews = [];

  final List<String> _allImages = [];

  double _totalSold = 0;

  bool _isDescriptionExpanded = false;

  int _selectedVariationIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _productDetail = widget.productDetail;

    _displayType = _productDetail.reviewDisplayType;

    _displayPolicy = _productDetail.reviewDisplayPolicy;

    _productInfo = _productDetail.productInfo;

    _productImages.addAll(_productInfo.images);

    _variants.addAll(_productInfo.variants);

    _allImages.addAll(_productImages);

    for (final variant in _variants) {
      _totalSold += variant.totalSold;
      final image = variant.image;
      if (image != null) {
        _allImages.add(image);
      }

      if (_displayPolicy == ReviewDisplayPolicy.all_rating) {
        _reviews.addAll(variant.reviews);
      } else {
        for (final review in variant.reviews) {
          if (review.ratingCount >= 4) {
            _reviews.add(review);
          }
        }
      }
    }
  }

  Future<void> _checkoutOrAddToCart({
    required int tempQuantity,
    required double sellingPrice,
    required bool isBuyNow,
  }) async {
    final outletId = ref.read(currentOutletIdProvider);

    var image = _productInfo.hasVariant
        ? _productInfo.variants[_selectedVariationIndex].image
        : _productInfo.images.lastOrNull;

    if (image == null) {
      image = _productInfo.images.lastOrNull;
    }

    final stockType = _variants[_selectedVariationIndex].stockType;

    final stock = _variants[_selectedVariationIndex].stock;

    final unit = _productInfo.unit;

    final cartItem = CartItem(
      id: _productInfo.variants[_selectedVariationIndex].id,
      outletId: outletId!,
      image: image,
      name: _productInfo.name,
      variantName: _variants[_selectedVariationIndex].name,
      isProductVariant: _variants[_selectedVariationIndex].isProductVariant,
      sellingPrice: sellingPrice,
      stockType: stockType.type,
      stock: stock,
      unit: unit,
      quantity: tempQuantity,
    );

    if (isBuyNow) {
      final isLoggedIn = ref.read(currentStatusLoginProvider);

      if (!isLoggedIn) {
        showModalBottomSheet(
          context: context,
          isScrollControlled: true,
          backgroundColor: Colors.transparent,
          constraints: BoxConstraints(maxWidth: double.infinity),
          builder: (context) => const LoginAuthModal(),
        );
        return;
      }

      ref.read(cartItemControllerProvider.notifier).clear();
      ref
          .read(cartItemControllerProvider.notifier)
          .increment(cartItem, quantity: tempQuantity);

      final cartItems = ref.read(cartItemProvider);

      await SystemSetting.saveCartItemByOutlet(cartItems);

      context.pushNamed(AppRoute.checkoutScreen);
    } else {
      ref
          .read(cartItemControllerProvider.notifier)
          .increment(cartItem, quantity: tempQuantity);

      final cartItems = ref.read(cartItemProvider);

      await SystemSetting.saveCartItemByOutlet(cartItems);

      CustomSnackbar.showSuccess(context, "Berhasil ditambahkan ke keranjang");

      context.goNamed(AppRoute.cartScreen);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _imageController.dispose();
    super.dispose();
  }

  void _showSelectedModal({required bool isBuyNow}) {
    bool showLimitMessage = false;

    bool showMaksMessage = false;

    int tempQuantity = 1;

    final hasVariant = _productInfo.hasVariant;

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: BoxConstraints(maxWidth: double.infinity),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            final image = hasVariant
                ? _variants[_selectedVariationIndex].image
                : _productInfo.images.firstOrNull;

            final sellingPrice =
                _variants[_selectedVariationIndex].sellingPrice;

            final totalOrder = sellingPrice * tempQuantity;

            final stockType = _variants[_selectedVariationIndex].stockType;

            final stock = _variants[_selectedVariationIndex].stock;

            final isAvailable =
                stockType == StockType.unlimited ||
                (stockType == StockType.fixed && stock > 0);
            return SafeArea(
              top: false,
              bottom: true,
              right: false,
              left: false,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(4.5.w),
                  ),
                ),
                constraints: BoxConstraints(maxWidth: double.infinity),
                padding: EdgeInsets.fromLTRB(4.w, 2.h, 4.w, 4.h),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        CachedNetworkImage(
                          imageUrl: image ?? '',
                          imageBuilder: (context, imageProvider) {
                            return Container(
                              width: 25.w,
                              height: 25.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(2.5.w),
                                image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            );
                          },
                          errorWidget: (context, url, error) {
                            return Container(
                              width: 25.w,
                              height: 25.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                              child: Center(
                                child: Icon(
                                  Icons.image_outlined,
                                  color: Colors.grey.shade300,
                                  size: 25.w,
                                ),
                              ),
                            );
                          },
                        ),

                        SizedBox(width: 4.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                CurrencyFormat.formatToIdr(totalOrder, 0),
                                style: TextStyle(
                                  color: AppColor.primaryColor,
                                  fontSize: AppFontSize.medium.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),

                              if (stockType == StockType.fixed) ...[
                                SizedBox(height: 1.5.h),

                                Text(
                                  stock <= 0
                                      ? "Stok Habis"
                                      : "Stok: " +
                                            stock
                                                .toStringWithoutTrailingZero() +
                                            " ${_productInfo.unit}",
                                  style: TextStyle(
                                    fontSize: (AppFontSize.small - 1.25).sp,
                                    color: Colors.grey.shade700,
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ),
                      ],
                    ),
                    if (_productInfo.hasVariant) ...[
                      Divider(height: 4.h),
                      Text(
                        "Varian",
                        style: TextStyle(
                          fontSize: (AppFontSize.small - 1.25).sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 1.5.h),
                      Wrap(
                        spacing: 2.w,
                        runSpacing: 1.h,
                        children: List.generate(_variants.length, (index) {
                          final variant = _variants[index];
                          final isSelected = _selectedVariationIndex == index;
                          return GestureDetector(
                            onTap: () {
                              setModalState(
                                () => _selectedVariationIndex = index,
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 4.w,
                                vertical: 1.5.h,
                              ),
                              decoration: BoxDecoration(
                                color: isSelected
                                    ? AppColor.primaryColor.withOpacity(0.15)
                                    : Colors.grey.shade100,
                                borderRadius: BorderRadius.circular(2.w),
                              ),
                              child: Text(
                                variant.name,
                                style: TextStyle(
                                  color: isSelected
                                      ? AppColor.primaryColor
                                      : Colors.black87,
                                  fontSize: (AppFontSize.small - 1.25).sp,
                                  fontWeight: isSelected
                                      ? FontWeight.bold
                                      : FontWeight.normal,
                                ),
                              ),
                            ),
                          );
                        }),
                      ),
                    ],
                    Divider(height: 4.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "Jumlah",
                          style: TextStyle(
                            fontSize: (AppFontSize.small - 1.25).sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Container(
                              decoration: BoxDecoration(
                                border: Border.all(color: Colors.grey.shade300),
                                borderRadius: BorderRadius.circular(1.5.w),
                              ),
                              child: Row(
                                children: [
                                  _buildQtyBtn(Icons.remove, () {
                                    if (tempQuantity > 1)
                                      setModalState(() {
                                        if (showMaksMessage) {
                                          showMaksMessage = false;
                                        }
                                        tempQuantity--;
                                      });
                                  }),
                                  Container(
                                    width: 12.w,
                                    alignment: Alignment.center,
                                    child: Text(
                                      "$tempQuantity",
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: (AppFontSize.small - 1.25).sp,
                                      ),
                                    ),
                                  ),
                                  _buildQtyBtn(Icons.add, () {
                                    if (showMaksMessage) return;

                                    if (stockType == StockType.fixed &&
                                        tempQuantity >= stock) {
                                      setModalState(
                                        () => showMaksMessage = true,
                                      );
                                      return;
                                    }
                                    setModalState(() => tempQuantity++);
                                  }),
                                ],
                              ),
                            ),
                            if (showMaksMessage) ...[
                              SizedBox(height: 0.75.h),
                              Text(
                                "Kuantitas mencapai batas maksimum",
                                style: TextStyle(
                                  color: Colors.red,
                                  fontSize: (AppFontSize.small - 1.25).sp,
                                ),
                              ),
                            ],
                          ],
                        ),
                      ],
                    ),
                    if (showLimitMessage) ...[
                      SizedBox(height: 1.h),
                      Text(
                        "Keranjang mencapai batas maksimum",
                        style: TextStyle(
                          color: Colors.red,
                          fontSize: (AppFontSize.small - 1.25).sp,
                        ),
                      ),
                    ],
                    SizedBox(height: 4.h),

                    SizedBox(
                      width: double.infinity,
                      height: 6.h,
                      child: ElevatedButton(
                        onPressed: !isAvailable
                            ? null
                            : () async {
                                final cartItems = ref.read(cartItemProvider);

                                final totalQuantity = cartItems.fold(0, (
                                  sum,
                                  cartItem,
                                ) {
                                  if (cartItem.id ==
                                      _variants[_selectedVariationIndex].id) {
                                    return sum + cartItem.quantity;
                                  }
                                  return 0;
                                });

                                if (!isBuyNow &&
                                    stockType == StockType.fixed &&
                                    ((totalQuantity + tempQuantity) > stock)) {
                                  setModalState(() => showLimitMessage = true);
                                  return;
                                }

                                await _checkoutOrAddToCart(
                                  tempQuantity: tempQuantity,
                                  sellingPrice: sellingPrice,
                                  isBuyNow: isBuyNow,
                                );
                              },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(1.5.w),
                          ),
                          disabledBackgroundColor: Colors.grey.shade300,
                        ),
                        child: Text(
                          isBuyNow ? "Beli Sekarang" : "Masukkan Keranjang",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: AppFontSize.medium.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF5F5F5),
            body: Stack(
              children: [
                SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildProductImageSlider(),

                      Container(
                        color: Colors.white,
                        padding: EdgeInsets.all(4.w),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _buildPriceAndActions(),
                            SizedBox(height: 1.h),
                            Text(
                              _productInfo.name,
                              style: TextStyle(
                                fontSize: AppFontSize.small.sp,
                                fontWeight: FontWeight.w500,
                                height: 1.4,
                              ),
                            ),
                          ],
                        ),
                      ),
                      if (_productInfo.hasVariant) _buildVariationSection(),

                      if (_productInfo.description != null &&
                          _productInfo.description!.isNotEmpty)
                        _buildDescriptionSection(),

                      _reviews.isEmpty
                          ? _buildEmptyReview()
                          : _buildReviewSection(),
                      SizedBox(height: 5.h),
                    ],
                  ),
                ),

                _buildTopOverlayButtons(),
              ],
            ),
            bottomNavigationBar: _buildBottomAppBar(),
          ),
        );
      },
    );
  }

  Widget _buildQtyBtn(IconData icon, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(1.h),
        child: Icon(icon, size: 5.w, color: Colors.grey.shade700),
      ),
    );
  }

  Widget _buildProductImageSlider() {
    if (_allImages.isEmpty) {
      return AspectRatio(
        aspectRatio: 1 / 1,
        child: Container(
          color: Colors.grey.shade100,
          child: Center(
            child: Icon(
              Icons.image_outlined,
              color: Colors.grey.shade300,
              size: 25.w,
            ),
          ),
        ),
      );
    }

    final stockType = _variants[_selectedVariationIndex].stockType;

    final stock = _variants[_selectedVariationIndex].stock;

    return AspectRatio(
      aspectRatio: 1 / 1,
      child: PageView.builder(
        controller: _imageController,
        itemCount: _allImages.length,
        onPageChanged: (index) {
          if (index >= _productImages.length) {
            setState(() {
              _selectedVariationIndex = index - _productImages.length;
            });
          }
        },
        itemBuilder: (context, index) {
          return Stack(
            children: [
              CachedNetworkImage(
                imageUrl: _allImages[index],
                imageBuilder: (context, imageProvider) {
                  return Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.5.w),
                      image: DecorationImage(
                        image: imageProvider,
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                },
                errorWidget: (context, url, error) {
                  return Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                    child: Center(
                      child: Icon(
                        Icons.image_outlined,
                        color: Colors.grey.shade300,
                        size: 25.w,
                      ),
                    ),
                  );
                },
              ),

              if (stockType == StockType.fixed && stock <= 0)
                Center(
                  child: Container(
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.75),
                      shape: BoxShape.circle,
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      "HABIS",
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: AppFontSize.small.sp,
                        letterSpacing: 1.5,
                      ),
                    ),
                  ),
                ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildPriceAndActions() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          CurrencyFormat.formatToIdr(
            _productInfo.variants[_selectedVariationIndex].sellingPrice,
            0,
          ),
          style: TextStyle(
            color: AppColor.primaryColor,
            fontSize: AppFontSize.large.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          "${_totalSold.toCompact} Terjual",
          style: TextStyle(
            fontSize: (AppFontSize.small - 1.25).sp,
            color: Colors.grey.shade700,
          ),
        ),
      ],
    );
  }

  Widget _buildVariationSection() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(4.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Pilihan Variasi",
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 2.h),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: List.generate(_variants.length, (index) {
                final variant = _variants[index];
                final isSelected = _selectedVariationIndex == index;
                return GestureDetector(
                  onTap: () {
                    setState(() => _selectedVariationIndex = index);
                    if (_variants[_selectedVariationIndex].image == null)
                      return;
                    _imageController.animateToPage(
                      _productImages.length + index,
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  },
                  child: _buildVariantCard(variant, isSelected),
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVariantCard(ProductVariant variant, bool isSelected) {
    return Container(
      margin: EdgeInsets.only(right: 3.w),
      padding: EdgeInsets.all(0.5.w),
      decoration: BoxDecoration(
        border: Border.all(
          color: isSelected ? AppColor.primaryColor : Colors.grey.shade300,
          width: 1,
        ),
        borderRadius: BorderRadius.circular(1.w),
      ),
      child: Row(
        children: [
          CachedNetworkImage(
            imageUrl: variant.image ?? '',
            imageBuilder: (context, imageProvider) {
              return Container(
                width: 12.5.w,
                height: 12.5.w,
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  image: DecorationImage(
                    image: imageProvider,
                    fit: BoxFit.cover,
                  ),
                ),
              );
            },
            errorWidget: (context, url, error) {
              return Container(
                width: 12.5.w,
                height: 12.5.w,
                decoration: BoxDecoration(color: Colors.grey.shade100),
                child: Center(
                  child: Icon(
                    Icons.image_outlined,
                    color: Colors.grey.shade300,
                    size: 5.w,
                  ),
                ),
              );
            },
          ),
          SizedBox(width: 2.5.w),
          Text(
            variant.name,
            style: TextStyle(fontSize: (AppFontSize.small - 1.25).sp),
          ),
          SizedBox(width: 2.5.w),
        ],
      ),
    );
  }

  Widget _buildDescriptionSection() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(4.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Deskripsi Produk",
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 1.h),
          Text(
            _productInfo.description ?? 'Deskripsi produk belum tersedia',
            maxLines: _isDescriptionExpanded ? 100 : 3,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              color: Colors.black87,
              height: 1.5,
            ),
          ),
          if (_productInfo.description != null)
            Center(
              child: TextButton.icon(
                style: TextButton.styleFrom(overlayColor: Colors.transparent),
                onPressed: () => setState(
                  () => _isDescriptionExpanded = !_isDescriptionExpanded,
                ),
                icon: Icon(
                  _isDescriptionExpanded
                      ? Icons.keyboard_arrow_up
                      : Icons.keyboard_arrow_down,
                  size: 5.w,
                  color: AppColor.primaryColor,
                ),
                label: Text(
                  _isDescriptionExpanded ? "Tutup" : "Selengkapnya",
                  style: TextStyle(
                    color: AppColor.primaryColor,
                    fontSize: AppFontSize.small.sp,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildReviewSection() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(4.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Penilaian Produk",
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          /**
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "Penilaian Produk",
                style: TextStyle(
                  fontSize: (AppFontSize.small - 1.25).sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                "Lihat Semua",
                style: TextStyle(
                  fontSize: (AppFontSize.small - 1.25).sp,
                  color: AppColor.primaryColor,
                ),
              ),
            ],
          ),
          */
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _reviews.length,
            separatorBuilder: (context, index) =>
                Divider(color: Colors.grey.shade200, thickness: 1),
            itemBuilder: (context, index) {
              final review = _reviews[index];
              return Padding(
                padding: EdgeInsets.symmetric(vertical: 1.h),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CircleAvatar(
                      radius: 5.w,
                      backgroundColor: Colors.grey.shade100,
                      child: Icon(
                        Icons.person,
                        color: Colors.grey.shade400,
                        size: 5.w,
                      ),
                    ),
                    SizedBox(width: 3.w),

                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            review.customerName,
                            style: TextStyle(
                              fontSize: (AppFontSize.small - 1.25).sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          SizedBox(height: 0.5.h),

                          Row(
                            children: List.generate(5, (starIndex) {
                              return Icon(
                                Icons.star,
                                size: 3.w,
                                color: starIndex < review.ratingCount
                                    ? Colors.orange
                                    : Colors.grey.shade300,
                              );
                            }),
                          ),
                          if (_displayType ==
                                  ReviewDisplayType.rating_and_review &&
                              review.comment != null) ...[
                            SizedBox(height: 1.h),
                            Text(
                              review.comment!,
                              style: TextStyle(
                                fontSize: (AppFontSize.small - 1.25).sp,
                                color: Colors.black87,
                                height: 1.4,
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyReview() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 4.w),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey.shade100)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.rate_review_outlined,
            size: AppFontSize.extraLarge.sp,
            color: Colors.grey.shade300,
          ),
          SizedBox(height: 2.h),
          Text(
            "Belum ada penilaian untuk produk ini",
            style: TextStyle(
              fontSize: AppFontSize.small.sp,
              color: Colors.grey.shade500,
              fontWeight: FontWeight.w400,
            ),
          ),
          SizedBox(height: 1.h),
          Text(
            "Jadilah yang pertama memberikan ulasan!",
            style: TextStyle(
              fontSize: (AppFontSize.small - 2).sp,
              color: Colors.grey.shade500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTopOverlayButtons() {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 1.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            CircleAvatar(
              backgroundColor: Colors.black.withOpacity(0.3),
              radius: 5.w,
              child: IconButton(
                icon: Icon(Icons.arrow_back, size: 5.w, color: Colors.white),
                onPressed: () => context.pop(),
              ),
            ),
            /**
            Row(
              children: [
                CircleAvatar(
                  backgroundColor: Colors.black.withOpacity(0.3),
                  radius: 5.w,
                  child: Icon(Icons.share, size: 5.w, color: Colors.white),
                ),
                SizedBox(width: 3.w),
                CircleAvatar(
                  backgroundColor: Colors.black.withOpacity(0.3),
                  radius: 5.w,
                  child: Icon(
                    Icons.shopping_cart,
                    size: 5.w,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            */
          ],
        ),
      ),
    );
  }

  Widget _buildBottomAppBar() {
    return Container(
      height: 8.h,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: InkWell(
              onTap: () => _showSelectedModal(isBuyNow: false),
              child: Icon(
                Icons.add_shopping_cart,
                color: AppColor.primaryColor,
                size: 5.w,
              ),
            ),
          ),
          Container(width: 1, height: 5.h, color: Colors.grey.shade200),
          Expanded(
            flex: 3,
            child: Container(
              color: AppColor.primaryColor,
              child: InkWell(
                onTap: () => _showSelectedModal(isBuyNow: true),
                child: Center(
                  child: Text(
                    "Beli Sekarang",
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: AppFontSize.medium.sp,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
