import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/dialog_dropdown.dart';
import 'package:syncrow_web/common/tag_dialog_textfield_dropdown.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/views/add_device_type_widget.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/helper/tag_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:uuid/uuid.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(
      {Key? 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})
      : super(key: key);

  @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: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(20),
                      child: DataTable(
                        headingRowColor: WidgetStateProperty.all(ColorsManager.dataHeaderGrey),
                        key: ValueKey(state.tags.length),
                        border: TableBorder.all(
                          color: ColorsManager.dataHeaderGrey,
                          width: 1,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        columns: [
                          DataColumn(
                              label: Text('#', style: Theme.of(context).textTheme.bodyMedium)),
                          DataColumn(
                              label: Text('Device', style: Theme.of(context).textTheme.bodyMedium)),
                          DataColumn(
                              numeric: false,
                              label: Text('Tag', style: Theme.of(context).textTheme.bodyMedium)),
                          DataColumn(
                              label:
                                  Text('Location', style: Theme.of(context).textTheme.bodyMedium)),
                        ],
                        rows: state.tags.isEmpty
                            ? [
                                DataRow(cells: [
                                  DataCell(
                                    Center(
                                      child: Text('No Data Available',
                                          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                                                color: ColorsManager.lightGrayColor,
                                              )),
                                    ),
                                  ),
                                  const DataCell(SizedBox()),
                                  const DataCell(SizedBox()),
                                  const DataCell(SizedBox()),
                                ])
                              ]
                            : List.generate(state.tags.length, (index) {
                                final tag = state.tags[index];
                                final controller = controllers[index];

                                return DataRow(
                                  cells: [
                                    DataCell(Text((index + 1).toString())),
                                    DataCell(
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Expanded(
                                              child: Text(
                                            tag.product?.name ?? 'Unknown',
                                            overflow: TextOverflow.ellipsis,
                                          )),
                                          const SizedBox(width: 10),
                                          Container(
                                            width: 20.0,
                                            height: 20.0,
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              border: Border.all(
                                                color: ColorsManager.lightGrayColor,
                                                width: 1.0,
                                              ),
                                            ),
                                            child: IconButton(
                                              icon: const Icon(
                                                Icons.close,
                                                color: ColorsManager.lightGreyColor,
                                                size: 16,
                                              ),
                                              onPressed: () {
                                                context.read<AssignTagBloc>().add(
                                                    DeleteTag(tagToDelete: tag, tags: state.tags));

                                                controllers.removeAt(index);
                                              },
                                              tooltip: 'Delete Tag',
                                              padding: EdgeInsets.zero,
                                              constraints: const BoxConstraints(),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    DataCell(
                                      Container(
                                        alignment:
                                            Alignment.centerLeft, // Align cell content to the left
                                        child: SizedBox(
                                          width: double.infinity,
                                          child: TagDialogTextfieldDropdown(
                                            key: ValueKey('dropdown_${const Uuid().v4()}_$index'),
                                            items: state.updatedTags,
                                            product: tag.product?.uuid ?? 'Unknown',
                                            initialValue: tag,
                                            onSelected: (value) {
                                              controller.text = value.tag ?? '';
                                              context.read<AssignTagBloc>().add(UpdateTagEvent(
                                                    index: index,
                                                    tag: value,
                                                  ));
                                            },
                                          ),
                                        ),
                                      ),
                                    ),
                                    DataCell(
                                      SizedBox(
                                          width: double.infinity,
                                          child: DialogDropdown(
                                            items: locations,
                                            selectedValue: tag.location ?? 'Main Space',
                                            onSelected: (value) {
                                              context.read<AssignTagBloc>().add(UpdateLocation(
                                                    index: index,
                                                    location: value,
                                                  ));
                                            },
                                          )),
                                    ),
                                  ],
                                );
                              }),
                      ),
                    ),
                    if (state.errorMessage != null)
                      Text(state.errorMessage!,
                          style: Theme.of(context)
                              .textTheme
                              .bodySmall
                              ?.copyWith(color: ColorsManager.warningRed)),
                  ],
                ),
              ),
              actions: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    const SizedBox(width: 10),
                    Expanded(
                      child: Builder(
                        builder: (buttonContext) => CancelButton(
                          label: 'Add New Device',
                          onPressed: () async {
                            final updatedTags = List<Tag>.from(state.tags);
                            final result = TagHelper.processTags(updatedTags, subspaces);

                            final processedTags = result['updatedTags'] as List<Tag>;
                            final processedSubspaces =
                                List<SubspaceModel>.from(result['subspaces'] as List<dynamic>);

                            Navigator.of(context).pop();

                            await showDialog(
                              context: context,
                              builder: (context) => AddDeviceTypeWidget(
                                products: products,
                                subspaces: processedSubspaces,
                                projectTags: projectTags,
                                initialSelectedProducts:
                                    TagHelper.createInitialSelectedProductsForTags(
                                        processedTags, processedSubspaces),
                                spaceName: spaceName,
                                spaceTags: processedTags,
                                isCreate: false,
                                onSave: onSave,
                                allTags: allTags,
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    Expanded(
                      child: DefaultButton(
                        borderRadius: 10,
                        backgroundColor: ColorsManager.secondaryColor,
                        foregroundColor: state.isSaveEnabled
                            ? ColorsManager.whiteColors
                            : ColorsManager.whiteColorsWithOpacity,
                        onPressed: state.isSaveEnabled
                            ? () async {
                                final updatedTags = List<Tag>.from(state.tags);
                                final result = TagHelper.processTags(updatedTags, subspaces);

                                final processedTags = result['updatedTags'] as List<Tag>;
                                final processedSubspaces =
                                    List<SubspaceModel>.from(result['subspaces'] as List<dynamic>);
                                onSave?.call(processedTags, processedSubspaces);
                                Navigator.of(context).pop();
                              }
                            : null,
                        child: const Text('Save'),
                      ),
                    ),
                    const SizedBox(width: 10),
                  ],
                ),
              ],
            );
          } else if (state is AssignTagLoading) {
            return const Center(child: CircularProgressIndicator());
          } else {
            return const Center(child: Text('Something went wrong.'));
          }
        },
      ),
    );
  }
}
