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/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.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/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.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_model_state.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/scrollable_grid_view_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class AddDeviceTypeModelWidget extends StatelessWidget {
  final List<ProductModel>? products;
  final List<SelectedProduct>? initialSelectedProducts;
  final List<SubspaceTemplateModel>? subspaces;
  final List<Tag>? spaceTagModels;
  final List<String>? allTags;
  final String spaceName;
  final bool isCreate;
  final List<String>? otherSpaceModels;
  final BuildContext? pageContext;
  final SpaceTemplateModel? spaceModel;
  final List<SpaceTemplateModel>? allSpaceModels;
  final List<Tag> projectTags;

  const AddDeviceTypeModelWidget(
      {super.key,
      this.products,
      this.initialSelectedProducts,
      this.subspaces,
      this.allTags,
      this.spaceTagModels,
      required this.spaceName,
      required this.isCreate,
      this.pageContext,
      this.otherSpaceModels,
      this.spaceModel,
      this.allSpaceModels,
      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: (_) => AddDeviceTypeModelBloc()
        ..add(InitializeDeviceTypeModel(
          initialTags: spaceTagModels ?? [],
          addedProducts: initialSelectedProducts ?? [],
        )),
      child: Builder(
        builder: (context) => AlertDialog(
          title: const Text('Add Devices'),
          backgroundColor: ColorsManager.whiteColors,
          content: BlocBuilder<AddDeviceTypeModelBloc, AddDeviceModelState>(
            builder: (context, state) {
              if (state is AddDeviceModelLoading) {
                return const Center(child: CircularProgressIndicator());
              }
              if (state is AddDeviceModelLoaded) {
                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(
                              isCreate: isCreate,
                              products: products,
                              crossAxisCount: crossAxisCount,
                              initialProductCounts: state.selectedProducts,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }
              return const SizedBox();
            },
          ),
          actions: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CancelButton(
                  label: 'Cancel',
                  onPressed: () async {
                    if (isCreate) {
                      Navigator.of(context).pop();
                      await showDialog(
                        context: context,
                        builder: (BuildContext dialogContext) {
                          return CreateSpaceModelDialog(
                            allSpaceModels: allSpaceModels,
                            products: products,
                            allTags: allTags,
                            projectTags: projectTags,
                            pageContext: pageContext,
                            otherSpaceModels: otherSpaceModels,
                            spaceModel: SpaceTemplateModel(
                                modelName: spaceName,
                                tags: spaceModel?.tags ?? [],
                                uuid: spaceModel?.uuid,
                                internalId: spaceModel?.internalId,
                                subspaceModels: subspaces),
                          );
                        },
                      );
                    } else {
                      final initialTags = TagHelper.generateInitialTags(
                        spaceTagModels: spaceTagModels,
                        subspaces: subspaces,
                      );

                      Navigator.of(context).pop();
                      await showDialog<bool>(
                          context: context,
                          builder: (context) => AssignTagModelsDialog(
                                products: products,
                                subspaces: subspaces,
                                addedProducts: initialSelectedProducts ?? [],
                                allTags: allTags,
                                projectTags: projectTags,
                                spaceName: spaceName,
                                initialTags: initialTags,
                                otherSpaceModels: otherSpaceModels,
                                title: 'Edit Device',
                                spaceModel: spaceModel,
                                pageContext: pageContext,
                              ));
                    }
                  },
                ),
                SizedBox(
                  width: 140,
                  child: BlocBuilder<AddDeviceTypeModelBloc, AddDeviceModelState>(
                    builder: (context, state) {
                      final isDisabled =
                          state is AddDeviceModelLoaded && state.selectedProducts.isEmpty;

                      return DefaultButton(
                        backgroundColor: ColorsManager.secondaryColor,
                        foregroundColor: isDisabled
                            ? ColorsManager.whiteColorsWithOpacity
                            : ColorsManager.whiteColors,
                        borderRadius: 10,
                        onPressed: isDisabled
                            ? null // Disable the button
                            : () async {
                                if (state is AddDeviceModelLoaded &&
                                    state.selectedProducts.isNotEmpty) {
                                  final initialTags = TagHelper.generateInitialTags(
                                    spaceTagModels: spaceTagModels,
                                    subspaces: subspaces,
                                  );

                                  final dialogTitle =
                                      initialTags.isNotEmpty ? 'Edit Device' : 'Assign Tags';
                                  Navigator.of(context).pop();
                                  await showDialog<bool>(
                                    context: context,
                                    builder: (context) => AssignTagModelsDialog(
                                      products: products,
                                      allSpaceModels: allSpaceModels,
                                      subspaces: subspaces,
                                      addedProducts: state.selectedProducts,
                                      allTags: allTags,
                                      projectTags: projectTags,
                                      spaceName: spaceName,
                                      initialTags: initialTags,
                                      otherSpaceModels: otherSpaceModels,
                                      title: dialogTitle,
                                      spaceModel: spaceModel,
                                      pageContext: pageContext,
                                    ),
                                  );
                                }
                              },
                        child: const Text('Next'),
                      );
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
