import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.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/bloc/add_device_type_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/widgets/scrollable_grid_view_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.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/assign_tag/views/assign_tag_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class AddDeviceTypeWidget extends StatelessWidget {
  final List<ProductModel>? products;
  final ValueChanged<List<SelectedProduct>>? onProductsSelected;
  final List<SelectedProduct>? initialSelectedProducts;
  final List<SubspaceModel>? subspaces;
  final List<Tag>? spaceTags;
  final List<String>? allTags;
  final String spaceName;
  final bool isCreate;
  final Function(List<Tag>, List<SubspaceModel>?)? onSave;
    final List<Tag> projectTags;


  const AddDeviceTypeWidget(
      {super.key,
      required this.isCreate,
      this.products,
      this.initialSelectedProducts,
      this.onProductsSelected,
      this.subspaces,
      this.allTags,
      this.spaceTags,
      this.onSave,
      required this.spaceName,
      required this.projectTags});

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final crossAxisCount = size.width > 1200
        ? 8
        : size.width > 800
            ? 5
            : 3;

    return BlocProvider(
        create: (_) => AddDeviceTypeBloc()
          ..add(InitializeDevice(
            initialTags: spaceTags ?? [],
            addedProducts: initialSelectedProducts ?? [],
          )),
        child: Builder(
          builder: (context) => AlertDialog(
            title: const Text('Add Devices'),
            backgroundColor: ColorsManager.whiteColors,
            content: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
                builder: (context, state) {
              if (state is AddDeviceLoading) {
                return const Center(child: CircularProgressIndicator());
              }
              if (state is AddDeviceLoaded) {
                return 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: ScrollableGridViewWidget(
                                initialProductCounts: state.selectedProducts,
                                products: products,
                                isCreate: isCreate,
                                crossAxisCount: crossAxisCount),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }
              return const SizedBox();
            }),
            actions: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CancelButton(
                    label: 'Cancel',
                    onPressed: () async {
                      Navigator.of(context).pop();
                    },
                  ),
                  SizedBox(
                      width: 140,
                      child: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
                        builder: (context, state) {
                          final isDisabled = state is AddDeviceLoaded &&
                              state.selectedProducts.isEmpty;
                          return DefaultButton(
                            borderRadius: 10,
                            backgroundColor: ColorsManager.secondaryColor,
                            foregroundColor: isDisabled
                                ? ColorsManager.whiteColorsWithOpacity
                                : ColorsManager.whiteColors,
                            onPressed: () async {
                              if (state is AddDeviceLoaded &&
                                  state.selectedProducts.isNotEmpty) {
                                final initialTags =
                                    TagHelper.generateInitialForTags(
                                  spaceTags: spaceTags,
                                  subspaces: subspaces,
                                );
                                Navigator.of(context).pop();

                                final dialogTitle = initialTags.isNotEmpty
                                    ? 'Edit Device'
                                    : 'Assign Tags';
                                await showDialog<bool>(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (context) => AssignTagDialog(
                                      products: products,
                                      subspaces: subspaces,
                                      addedProducts: state.selectedProducts,
                                      allTags: allTags,
                                      spaceName: spaceName,
                                      initialTags: initialTags,
                                      title: dialogTitle,
                                      onSave: onSave,
                                      projectTags: projectTags),
                                );
                              }
                            },
                            child: const Text('Next'),
                          );
                        },
                      )),
                ],
              ),
            ],
          ),
        ));
  }
}
