import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/widgets/device_type_tile_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';

class ScrollableGridViewWidget extends StatelessWidget {
  final List<ProductModel>? products;
  final int crossAxisCount;
  final List<SelectedProduct>? initialProductCounts;
  final bool isCreate;

  const ScrollableGridViewWidget(
      {super.key,
      required this.products,
      required this.crossAxisCount,
      this.initialProductCounts,
      required this.isCreate});

  @override
  Widget build(BuildContext context) {
    final scrollController = ScrollController();

    return Scrollbar(
      controller: scrollController,
      thumbVisibility: true,
      child: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
        builder: (context, state) {
          final productCounts = state is AddDeviceLoaded
              ? state.selectedProducts
              : <SelectedProduct>[];
          return GridView.builder(
            controller: scrollController,
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: crossAxisCount,
              mainAxisSpacing: 6,
              crossAxisSpacing: 4,
              childAspectRatio: .8,
            ),
            itemCount: products?.length ?? 0,
            itemBuilder: (context, index) {
              final product = products![index];
              final initialProductCount = _findInitialProductCount(product);

              return DeviceTypeTileWidget(
                product: product,
                isCreate: isCreate,
                productCounts: initialProductCount != null
                    ? [...productCounts, initialProductCount]
                    : productCounts,
              );
            },
          );
        },
      ),
    );
  }

  SelectedProduct? _findInitialProductCount(ProductModel product) {
    if (initialProductCounts == null) return null;
    final matchingProduct = initialProductCounts!.firstWhere(
      (selectedProduct) => selectedProduct.productId == product.uuid,
      orElse: () => SelectedProduct(
        productId: '',
        count: 0,
        productName: '',
        product: null,
      ),
    );

    return matchingProduct.productId.isNotEmpty ? matchingProduct : null;
  }
}
