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/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/widgets/assign_tags_tables_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';

import 'widgets/save_add_device_row_widget.dart';

class AssignTagDialog extends StatelessWidget {
  final List<ProductModel>? products;
  final List<SubspaceModel>? subspaces;
  final List<Tag>? initialTags;
  final ValueChanged<List<Tag>>? onTagsAssigned;
  final List<SelectedProduct> addedProducts;
  final List<String>? allTags;
  final String spaceName;
  final String title;
  final Function(List<Tag>, List<SubspaceModel>?)? onSave;
  final List<Tag> projectTags;

  const AssignTagDialog(
      {super.key,
      required this.products,
      required this.subspaces,
      required this.addedProducts,
      this.initialTags,
      this.onTagsAssigned,
      this.allTags,
      required this.spaceName,
      required this.title,
      this.onSave,
      required this.projectTags});

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

    return BlocProvider(
      create: (_) => AssignTagBloc(projectTags)
        ..add(InitializeTags(
          initialTags: initialTags,
          addedProducts: addedProducts,
        )),
      child: BlocBuilder<AssignTagBloc, AssignTagState>(
        builder: (context, state) {
          if (state is AssignTagLoaded) {
            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<AssignTagBloc>()
                            .add(DeleteTag(tagToDelete: tag, tags: state.tags));

                        controllers.removeAt(index);
                      },
                      onTagDropDownSelected: ({required index, required tag}) {
                        context.read<AssignTagBloc>().add(UpdateTagEvent(
                              index: index,
                              tag: tag,
                            ));
                      },
                      onLocationDropDownSelected: (
                          {required index, required location}) {
                        context.read<AssignTagBloc>().add(UpdateLocation(
                              index: index,
                              location: location,
                            ));
                      },
                    ),
                    if (state.errorMessage != null)
                      Text(state.errorMessage!,
                          style: Theme.of(context)
                              .textTheme
                              .bodySmall
                              ?.copyWith(color: ColorsManager.warningRed)),
                  ],
                ),
              ),
              actions: [
                SaveAddDeviceRowWidget(
                  subspaces: subspaces,
                  products: products,
                  projectTags: projectTags,
                  spaceName: spaceName,
                  onSave: onSave,
                  allTags: allTags,
                  tags: state.tags,
                  isSaveEnabled: state.isSaveEnabled,
                ),
              ],
            );
          } else if (state is AssignTagLoading) {
            return const Center(child: CircularProgressIndicator());
          } else {
            return const Center(child: Text('Something went wrong.'));
          }
        },
      ),
    );
  }
}
