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/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/bloc/assign_tag_model_state.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/utils/color_manager.dart';

import 'widgets/RowOfCancelSaveWidget.dart';
import 'widgets/assign_tags_tables_widget.dart';

class AssignTagModelsDialog extends StatelessWidget {
  final List<ProductModel>? products;
  final List<SubspaceTemplateModel>? subspaces;
  final SpaceTemplateModel? spaceModel;

  final List<Tag> initialTags;
  final ValueChanged<List<Tag>>? onTagsAssigned;
  final List<SelectedProduct> addedProducts;
  final List<String>? allTags;
  final String spaceName;
  final String title;
  final BuildContext? pageContext;
  final List<String>? otherSpaceModels;
  final List<SpaceTemplateModel>? allSpaceModels;
  final List<Tag> projectTags;

  const AssignTagModelsDialog(
      {Key? key,
      required this.products,
      required this.subspaces,
      required this.addedProducts,
      required this.initialTags,
      this.onTagsAssigned,
      this.allTags,
      required this.spaceName,
      required this.title,
      this.pageContext,
      this.otherSpaceModels,
      this.spaceModel,
      this.allSpaceModels,
      required this.projectTags})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final List<String> locations = (subspaces ?? [])
        .map((subspace) => subspace.subspaceName)
        .toList()
      ..add('Main Space');

    return BlocProvider(
        create: (_) => AssignTagModelBloc(projectTags)
          ..add(InitializeTagModels(
            initialTags: initialTags,
            addedProducts: addedProducts,
          )),
        child: BlocListener<AssignTagModelBloc, AssignTagModelState>(
          listener: (context, state) {},
          child: BlocBuilder<AssignTagModelBloc, AssignTagModelState>(
            builder: (context, state) {
              if (state is AssignTagModelLoaded) {
                final controllers = List.generate(
                  state.tags.length,
                  (index) => TextEditingController(text: state.tags[index].tag),
                );

                return AlertDialog(
                  title: Text(title),
                  backgroundColor: ColorsManager.whiteColors,
                  content: SingleChildScrollView(
                    child: Column(
                      children: [
                        AssignTagsTable(
                          controllers: controllers,
                          locations: locations,
                          tags: state.tags,
                          updatedTags: state.updatedTags,
                          onDeleteDevice: ({required index, required tag}) {
                            context
                                .read<AssignTagModelBloc>()
                                .add(DeleteTagModel(
                                  tagToDelete: tag,
                                  tags: state.tags,
                                ));
                            controllers.removeAt(index);
                          },
                          onTagDropDownSelected: (
                              {required index, required tag}) {
                            context.read<AssignTagModelBloc>().add(
                                  UpdateTag(
                                    index: index,
                                    tag: tag,
                                  ),
                                );
                          },
                          onLocationDropDownSelected: (
                              {required index, required location}) {
                            context.read<AssignTagModelBloc>().add(
                                  UpdateLocation(
                                    index: index,
                                    location: location,
                                  ),
                                );
                          },
                        ),
                        if (state.errorMessage != null)
                          Text(state.errorMessage!,
                              style: Theme.of(context)
                                  .textTheme
                                  .bodySmall
                                  ?.copyWith(color: ColorsManager.warningRed)),
                      ],
                    ),
                  ),
                  actions: [
                    RowOfSaveCancelWidget(
                      subspaces: subspaces,
                      products: products,
                      allTags: allTags,
                      spaceName: spaceName,
                      otherSpaceModels: otherSpaceModels,
                      pageContext: pageContext,
                      projectTags: projectTags,
                      spaceModel: spaceModel,
                      allSpaceModels: allSpaceModels,
                    ),
                  ],
                );
              } else if (state is AssignTagModelLoading) {
                return const Center(child: CircularProgressIndicator());
              } else {
                return const Center(child: Text('Something went wrong.'));
              }
            },
          ),
        ));
  }
}
