import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import '../../voucher/models/product_model.dart';
import '../../voucher/sub_widget/voucher_section_title.dart';
import '../models/main_section_config_model.dart';
import 'flash_sale_header_widget.dart';

class FlashSaleCarouselWidget extends StatefulWidget {
  final List<ProductModel> products;
  final MainSectionConfigModel? sectionConfig;
  final void Function(ProductModel)? onTap;

  const FlashSaleCarouselWidget({super.key, required this.products, this.sectionConfig, this.onTap});

  @override
  State<FlashSaleCarouselWidget> createState() => _FlashSaleCarouselWidgetState();
}

class _FlashSaleCarouselWidgetState extends State<FlashSaleCarouselWidget> {
  _handleTapRightButton() {
    widget.sectionConfig?.buttonViewAll?.directionalScreen?.begin();
  }

  @override
  Widget build(BuildContext context) {
    final widthItem = MediaQuery.of(context).size.width / 2.5;
    final heightItem = widthItem * 9 / 16 + (widget.products.firstOrNull?.extendSpaceFlashSaleItem ?? 130);
    if (widget.products.isEmpty) return const SizedBox.shrink();
    return Column(
      children: [
        if (widget.sectionConfig?.flashSale != null)
          FlashSaleHeader(
            flashSale: widget.sectionConfig?.flashSale,
            onViewAll: widget.sectionConfig?.buttonViewAll?.directionalScreen != null ? _handleTapRightButton : null,
          ),
        const SizedBox(height: 8),
        ConstrainedBox(
          constraints: BoxConstraints(maxHeight: heightItem),
          child: ListView.separated(
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: widget.products.length,
            separatorBuilder: (_, __) => const SizedBox(width: 12),
            itemBuilder: (context, index) => _buildFlashSaleGridItem(widget.products[index]),
          ),
        ),
      ],
    );
  }

  Widget _buildFlashSaleGridItem(ProductModel product) {
    final widthItem = MediaQuery.of(context).size.width / 2.5;
    return GestureDetector(
      onTap: () => widget.onTap?.call(product),
      child: Container(
        width: widthItem,
        margin: const EdgeInsets.symmetric(horizontal: 0),
        padding: const EdgeInsets.all(0),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade200),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Hình ảnh + tag % giảm
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
                  child: Image.network(
                    product.banner?.url ?? '',
                    width: double.infinity,
                    height: widthItem * 9 / 16,
                    fit: BoxFit.cover,
                  ),
                ),
                if (product.percentDiscount != null)
                  Positioned(
                    right: 4,
                    bottom: 4,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(20)),
                      child: Text(
                        '-${product.percentDiscount}%',
                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12),
                      ),
                    ),
                  ),
              ],
            ),
            // const SizedBox(height: 8),
            // Giá khuyến mãi + gạch giá gốc
            Container(
              padding: const EdgeInsets.all(4),
              child: Column(
                children: [
                  SizedBox(
                    height: 24,
                    child: Row(
                      children: [
                        Image.asset("assets/images/ic_hot_flash_sale.png", width: 20, height: 20, fit: BoxFit.cover),
                        // if (product.previewFlashSale?.price != null)
                        Text(
                          "${product.amountToBePaid?.money(CurrencyUnit.noneSpace)}đ",
                          // '${product.previewFlashSale?.price}đ',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(width: 2),
                        if (product.price?.value != null)
                          Text(
                            '${product.price?.value?.money(CurrencyUnit.noneSpace)}đ',
                            style: const TextStyle(
                              fontSize: 12,
                              color: Colors.grey,
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    product.name ?? '',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 13),
                  ),
                  const SizedBox(height: 4),
                  // Button Nhận quà / điểm
                  if (product.previewFlashSale?.rewardContent != null)
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.orange),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              product.previewFlashSale?.imageReward ?? 'assets/images/ic_gift_flash_sale.png',
                              width: 16,
                              height: 16,
                              color: Colors.orange,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              product.previewFlashSale?.rewardContent ?? 'Nhận quà',
                              style: const TextStyle(fontSize: 12, color: Colors.orange, fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                      ),
                    ),
                  // Thanh tiến trình + Số lượng đã bán
                  if (product.isShowProsessSoldItem)
                    Column(
                      children: [
                        const SizedBox(height: 4),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            // Thanh tiến trình
                            SizedBox(
                              width: widthItem - 90,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(4),
                                child: LinearProgressIndicator(
                                  value: product.progress,
                                  minHeight: 6,
                                  backgroundColor: Colors.grey.shade300,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    product.inStock ? Colors.orange : Colors.red,
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(width: 2),
                            Text(
                              product.inStock
                                  ? 'Đã bán ${product.previewFlashSale?.fsQuantitySold ?? 0}'
                                  : 'Đã bán hết',
                              style: TextStyle(fontSize: 12, color: product.inStock ? Colors.black : Colors.grey),
                            ),
                          ],
                        ),
                      ],
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
