import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import '../model/affiliate_product_top_sale_model.dart';

class AffiliateProductTopSale extends StatelessWidget {
  final List<AffiliateProductTopSaleModel> products;

  const AffiliateProductTopSale({super.key, required this.products});

  @override
  Widget build(BuildContext context) {
    if (products.isEmpty) {
      return const SizedBox.shrink();
    }
    final double screenWidth = MediaQuery.of(context).size.width;
    final double itemWidth = (screenWidth - 24) / 2;
    final double itemHeight = itemWidth + 104;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 24),
        Text("Sản Phẩm Bán Chạy", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
        const SizedBox(height: 12),
        GridView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: products.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: itemWidth / itemHeight,
            crossAxisSpacing: 8,
            mainAxisSpacing: 8,
          ),
          itemBuilder: (context, index) {
            final product = products[index];
            return _buildAffiliateProductTopSaleItem(product);
          },
        ),
      ],
    );
  }

  Widget _buildAffiliateProductTopSaleItem(AffiliateProductTopSaleModel product) {
    final price = product.productPrice ?? '';
    final formatter = NumberFormat.currency(locale: 'vi_VN', symbol: 'VNĐ', decimalDigits: 0);
    final formattedPrice = formatter.format(double.tryParse(price) ?? 0);
    final commission = product.commision ?? '';
    final sold = product.quantitySold ?? '';
    final imageUrl = product.thumnailLink ?? '';
    final title = product.productName ?? '';

    return GestureDetector(
      onTap: () => product.direcionalScreen?.begin(),
      child: Container(
        width: 160,
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 4, offset: const Offset(0, 2))],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: AspectRatio(
                aspectRatio: 1,
                child: Image.network(
                  imageUrl,
                  fit: BoxFit.cover,
                  errorBuilder: (_, _, _) => Image.asset('assets/images/bg_default_11.png'),
                ),
              ),
            ),
            const SizedBox(height: 6),
            Text(title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13)),
            const SizedBox(height: 4),
            Text(
              formattedPrice,
              style: const TextStyle(color: Colors.blueAccent, fontSize: 14, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 2),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                RichText(
                  text: TextSpan(
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                    children: [
                      const TextSpan(text: "Hoàn đến: "),
                      TextSpan(
                        text: "${(commission).toNum()?.toString() ?? ''}%",
                        style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold, fontSize: 14),
                      ),
                    ],
                  ),
                ),
                Flexible(
                  child: Text(
                    "${sold.toNum()?.formatCompactNumber()} đã bán",
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ),
              ],
            ),
          ],
        )
      ),
    );
  }
}
