import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/counter_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/device_icon_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/device_name_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';

class DeviceTypeTileWidget extends StatelessWidget {
  final ProductModel product;
  final List<SelectedProduct> productCounts;
  final bool isCreate;

  const DeviceTypeTileWidget(
      {super.key,
      required this.product,
      required this.productCounts,
      required this.isCreate});

  @override
  Widget build(BuildContext context) {
    final selectedProduct = productCounts.firstWhere(
      (p) => p.productId == product.uuid,
      orElse: () => SelectedProduct(
          productId: product.uuid,
          count: 0,
          productName: product.catName,
          product: product),
    );

    return Card(
      elevation: 2,
      color: ColorsManager.whiteColors,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            DeviceIconWidget(icon: product.icon ?? Assets.doorSensor),
            const SizedBox(height: 4),
            DeviceNameWidget(name: product.name),
            const SizedBox(height: 4),
            CounterWidget(
              isCreate: isCreate,
              initialCount: selectedProduct.count,
              onCountChanged: (newCount) {
                context.read<AddDeviceTypeModelBloc>().add(
                      UpdateProductCountEvent(
                        selectedProduct: product.toSelectedProduct(
                          newCount,
                        ),
                      ),
                    );
              },
            ),
          ],
        ),
      ),
    );
  }
}
