import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../resources/base_color.dart';
import '../../widgets/custom_navigation_bar.dart';
import '../affiliate/affiliate_popup_brands.dart';
import '../affiliate/model/affiliate_category_model.dart';
import 'affiliate_category_grid_viewmodel.dart';

class AffiliateCategoryGridScreen extends StatefulWidget {
  const AffiliateCategoryGridScreen({super.key});

  @override
  _AffiliateCategoryGridScreenState createState() => _AffiliateCategoryGridScreenState();
}

class _AffiliateCategoryGridScreenState extends State<AffiliateCategoryGridScreen> {
  final AffiliateCategoryGridViewModel viewModel = Get.put(AffiliateCategoryGridViewModel());
  List<AffiliateCategoryModel> _categories = [];

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      _categories = args['categories'];
    }
    viewModel.onShowAffiliateBrandPopup = (data) {
      showAffiliateBrandPopup(context, data.$1, title: data.$2);
    };
  }

  @override
  Widget build(BuildContext context) {
    final space = 8.0;
    final width = (MediaQuery.of(context).size.width - space * 5) / 4;
    return Scaffold(
      appBar: CustomNavigationBar(title: "Lĩnh vực hoàn điểm"),
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 4,
            childAspectRatio: width / (width + 30),
            children: _categories.map((category) => _buildAffiliateCategoryItem(category)).toList(),
          ),
        ),
      ),
    );
  }

  Widget _buildAffiliateCategoryItem(AffiliateCategoryModel category) {
    return GestureDetector(
      onTap: () {
        viewModel.affiliateBrandGetListBuyCategory(category);
      },
      child: LayoutBuilder(
        builder: (context, constraints) {
          final double imageWidth = constraints.maxWidth / 2;
          return Container(
            padding: const EdgeInsets.only(top: 12, bottom: 8, left: 4, right: 4),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Image.asset('assets/images/cashback/${category.icon}.png', width: imageWidth, height: imageWidth),
                const SizedBox(height: 4),
                Text(
                  category.name ?? '',
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14, color: BaseColor.second500),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
