import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../../../shared/router_gage.dart';
import '../../../widgets/custom_price_tag.dart';
import '../../../widgets/image_loader.dart';
import '../models/product_model.dart';

class VoucherItemGrid extends StatelessWidget {
  final List<ProductModel> items;
  const VoucherItemGrid({super.key, required this.items});

  @override
  Widget build(BuildContext context) {
    final double itemWidth = MediaQuery.of(context).size.width * 0.7;
    final double imageHeight = itemWidth / (16 / 9);
    final double totalHeight = imageHeight + 80;

    return SizedBox(
      height: totalHeight,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: items.length,
        separatorBuilder: (context, index) => const SizedBox(width: 12),
        itemBuilder: (context, index) {
          final product = items[index];
          return GestureDetector(
            onTap: () {
              Get.toNamed(voucherDetailScreen, arguments: {"productId": product.id});
            },
            child: _VoucherGridItem(
              product: product,
              itemWidth: itemWidth,
            ),
          );
        },
      ),
    );
  }

}

class _VoucherGridItem extends StatelessWidget {
  final ProductModel product;
  final double itemWidth;

  const _VoucherGridItem({
    super.key,
    required this.product,
    required this.itemWidth,
  });

  @override
  Widget build(BuildContext context) {
    final hasDiscount = product.properties?.title != null;
    final brandName = product.brand?.name ?? '';
    final brandLogo = product.brand?.logo ?? "";
    final String? bgImage = product.banner?.url;

    return Container(
      width: itemWidth,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade200),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(
            children: [
              ClipRRect(
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(8),
                  topRight: Radius.circular(8),
                ),
                child: SizedBox(
                  width: itemWidth,
                  height: itemWidth / (16 / 9),
                  child: loadNetworkImage(
                      url: bgImage,
                      placeholderAsset: "assets/images/ic_logo.png"),
                ),
              ),
              if (hasDiscount)
                Positioned(
                  top: 0,
                  right: 0,
                  child: Container(
                    height: 30,
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(8),
                        topRight: Radius.circular(8),
                      ),
                    ),
                    child: Center(
                      child: Text(
                      product.properties?.title ?? "",
                        style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ),
              if (!product.inStock)
                Positioned(
                  left: 0,
                  bottom: 0,
                  child: Container(
                    height: 30,
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: const BorderRadius.only(
                        topRight: Radius.circular(8),
                      ),
                    ),
                    child: Center(
                      child: const Text(
                        'Tạm hết',
                        style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxHeight: 70), // ✅ Không cứng height, mà giới hạn max
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 4),
                  // Title: auto co giãn nhưng không tràn
                  Text(
                    product.content?.name ?? '',
                    style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const Spacer(), // ✅ Spacer đẩy info xuống dưới nhưng không gây overflow
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      CircleAvatar(
                        radius: 10,
                        backgroundColor: Colors.transparent,
                        child: ClipOval(
                          child: loadNetworkImage(
                            url: brandLogo,
                            width: 20,
                            height: 20,
                            fit: BoxFit.cover,
                            placeholderAsset: 'assets/images/ic_logo.png',
                          ),
                        ),
                      ),
                      const SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          brandName,
                          style: const TextStyle(fontSize: 11),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      PriceTagWidget(point: product.amountToBePaid ?? 0, type: product.price?.method),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
