import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import '../../affiliate/model/affiliate_brand_model.dart';
import '../../voucher/sub_widget/voucher_section_title.dart';
import '../models/main_section_config_model.dart';

class AffiliateBrandGridWidget extends StatelessWidget {
  final List<AffiliateBrandModel> affiliateBrands;
  final MainSectionConfigModel? sectionConfig;
  final void Function(AffiliateBrandModel)? onTap;

  const AffiliateBrandGridWidget({super.key, required this.affiliateBrands, this.sectionConfig, this.onTap});

  void _handleTapRightButton() {
    sectionConfig?.buttonViewAll?.directionalScreen?.begin();
  }

  @override
  Widget build(BuildContext context) {
    if (affiliateBrands.isEmpty) {
      return const SizedBox.shrink();
    }
    return Column(
      children: [
        if ((sectionConfig?.name ?? "").isNotEmpty)
          HeaderSectionTitle(
            title: sectionConfig?.name?? "",
            onViewAll: sectionConfig?.buttonViewAll?.directionalScreen != null ? _handleTapRightButton : null,
          ),
        GridView.builder(
          padding: EdgeInsets.all(12),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: affiliateBrands.length,
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 3 / 3,
            crossAxisSpacing: 12,
            mainAxisSpacing: 12,
          ),
          itemBuilder: (context, index) {
            final brand = affiliateBrands[index];
            return _buildAffiliateBrandItem(brand);
          },
        ),
      ],
    );
  }

  Widget _buildAffiliateBrandItem(AffiliateBrandModel brand) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final double imageWidth = constraints.maxWidth / 2.5;
        return Container(
          padding: const EdgeInsets.all(4),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.08),
                blurRadius: 5,
                offset: const Offset(-2, 2),
              )
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                width: imageWidth,
                height: imageWidth, // ✅ 1:1 tỉ lệ
                child: ClipOval(
                  child: Image.network(
                    brand.logo ?? '',
                    fit: BoxFit.contain,
                    errorBuilder: (_, _, _) => const Icon(Icons.broken_image),
                  ),
                ),
              ),
              const SizedBox(height: 2),
              Text(
                brand.brandName ?? "",
                maxLines: 2,
                textAlign: TextAlign.center,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
              ),
              const SizedBox(height: 4),
              RichText(
                textAlign: TextAlign.center,
                text: TextSpan(
                  style: const TextStyle(fontSize: 12),
                  children: [
                    const TextSpan(
                      text: "Hoàn đến: ",
                      style: TextStyle(color: Colors.grey),
                    ),
                    TextSpan(
                      text: "${(brand.commision ?? '').toNum()?.toString() ?? ''}%",
                      style: const TextStyle(
                        color: Colors.orange,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
