import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.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/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class AddDeviceWidget extends StatefulWidget {
  final List<ProductModel>? products;
  final ValueChanged<List<SelectedProduct>>? onProductsSelected;
  final List<SelectedProduct>? initialSelectedProducts;

  const AddDeviceWidget({
    super.key,
    this.products,
    this.initialSelectedProducts,
    this.onProductsSelected,
  });

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

class _AddDeviceWidgetState extends State<AddDeviceWidget> {
  late final ScrollController _scrollController;
  late List<SelectedProduct> productCounts;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    productCounts =
        widget.initialSelectedProducts != null ? List.from(widget.initialSelectedProducts!) : [];
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    // Adjust the GridView properties based on screen width
    final crossAxisCount = size.width > 1200
        ? 8
        : size.width > 800
            ? 5
            : 3;

    return AlertDialog(
      title: const Text('Add Devices'),
      backgroundColor: ColorsManager.whiteColors,
      content: SingleChildScrollView(
        child: Container(
          width: size.width * 0.9,
          height: size.height * 0.65,
          color: ColorsManager.textFieldGreyColor,
          child: Column(
            children: [
              const SizedBox(height: 16),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0),
                  child: Scrollbar(
                    controller: _scrollController,
                    thumbVisibility: false,
                    child: GridView.builder(
                      shrinkWrap: true,
                      controller: _scrollController,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: crossAxisCount,
                        mainAxisSpacing: 6,
                        crossAxisSpacing: 4,
                        childAspectRatio: .8,
                      ),
                      itemCount: widget.products?.length ?? 0,
                      itemBuilder: (context, index) {
                        final product = widget.products![index];
                        return _buildDeviceTypeTile(product, size);
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      actions: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildActionButton('Cancel', ColorsManager.boxColor, ColorsManager.blackColor, () {
              Navigator.of(context).pop();
            }),
            _buildActionButton('Continue', ColorsManager.secondaryColor, ColorsManager.whiteColors, () {
              Navigator.of(context).pop();
              if (widget.onProductsSelected != null) {
                widget.onProductsSelected!(productCounts);
              }
            }),
          ],
        ),
      ],
    );
  }

  Widget _buildDeviceTypeTile(ProductModel product, Size size) {
    final selectedProduct = productCounts.firstWhere(
      (p) => p.productId == product.uuid,
      orElse: () => SelectedProduct(productId: product.uuid, count: 0, productName: product.catName, product: product),
    );

    return SizedBox(
      width: size.width * 0.12,
      height: size.height * 0.15,
      child: 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: [
              _buildDeviceIcon(product, size),
              const SizedBox(height: 4),
              _buildDeviceName(product, size),
              const SizedBox(height: 4),
              CounterWidget(
                isCreate: false,
                initialCount: selectedProduct.count,
                onCountChanged: (newCount) {
                  setState(() {
                    if (newCount > 0) {
                      if (!productCounts.contains(selectedProduct)) {
                        productCounts
                            .add(SelectedProduct(productId: product.uuid, count: newCount, productName: product.catName, product: product));
                      } else {
                        selectedProduct.count = newCount;
                      }
                    } else {
                      productCounts.removeWhere((p) => p.productId == product.uuid);
                    }

                    if (widget.onProductsSelected != null) {
                      widget.onProductsSelected!(productCounts);
                    }
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDeviceIcon(ProductModel product, Size size) {
    return Container(
      height: size.width > 800 ? 50 : 40,
      width: size.width > 800 ? 50 : 40,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: ColorsManager.textFieldGreyColor,
        border: Border.all(
          color: ColorsManager.neutralGray,
          width: 2,
        ),
      ),
      child: Center(
        child: SvgPicture.asset(
          product.icon ?? Assets.sensors,
          width: size.width > 800 ? 30 : 20,
          height: size.width > 800 ? 30 : 20,
        ),
      ),
    );
  }

  Widget _buildDeviceName(ProductModel product, Size size) {
    return SizedBox(
      height: size.width > 800 ? 35 : 25,
      child: Text(
        product.name ?? '',
        style: context.textTheme.bodySmall?.copyWith(color: ColorsManager.blackColor),
        textAlign: TextAlign.center,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Widget _buildActionButton(
    String label,
    Color backgroundColor,
    Color foregroundColor,
    VoidCallback onPressed,
  ) {
    return SizedBox(
      width: 120,
      child: DefaultButton(
        onPressed: onPressed,
        backgroundColor: backgroundColor,
        foregroundColor: foregroundColor,
        child: Text(label),
      ),
    );
  }
}
