import 'package:flutter/material.dart';
import 'package:syncrow_web/common/edit_chip.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.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/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/views/create_subspace_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class SubspaceModelCreate extends StatefulWidget {
  final List<SubspaceTemplateModel> subspaces;
  final void Function(
          List<SubspaceTemplateModel> newSubspaces, List<Tag>? tags)?
      onSpaceModelUpdate;
  final List<Tag> tags;

  const SubspaceModelCreate({
    Key? key,
    required this.subspaces,
    this.onSpaceModelUpdate,
    required this.tags,
  }) : super(key: key);

  @override
  _SubspaceModelCreateState createState() => _SubspaceModelCreateState();
}

class _SubspaceModelCreateState extends State<SubspaceModelCreate> {
  late List<SubspaceTemplateModel> _subspaces;
  String? errorSubspaceId;
  late List<Tag> _tags;

  @override
  void initState() {
    super.initState();
    _subspaces = List.from(widget.subspaces);
    _tags = List.from(widget.tags);
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    return Container(
      child: _subspaces.isEmpty
          ? TextButton(
              style: TextButton.styleFrom(
                overlayColor: ColorsManager.transparentColor,
              ),
              onPressed: () async {
                await _openDialog(context, 'Create Sub-space');
              },
              child: const ButtonContentWidget(
                icon: Icons.add,
                label: 'Create Sub Space',
              ),
            )
          : SizedBox(
              width: screenWidth * 0.25,
              child: Container(
                padding: const EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  color: ColorsManager.textFieldGreyColor,
                  borderRadius: BorderRadius.circular(15),
                  border: Border.all(
                    color: ColorsManager.textFieldGreyColor,
                    width: 3.0,
                  ),
                ),
                child: Wrap(
                  spacing: 8.0,
                  runSpacing: 8.0,
                  children: [
                    ..._subspaces.map((subspace) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SubspaceNameDisplayWidget(
                            text: subspace.subspaceName,
                            validateName: (updatedName) {
                              return !_subspaces.any((s) =>
                                  s != subspace &&
                                  s.subspaceName == updatedName);
                            },
                            onNameChanged: (updatedName) {
                              setState(() {
                                subspace.subspaceName = updatedName;
                              });
                            },
                          ),
                        ],
                      );
                    }),
                    EditChip(
                      onTap: () async {
                        await _openDialog(context, 'Edit Sub-space');
                      },
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  Future<void> _openDialog(BuildContext context, String dialogTitle) async {
    await showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return CreateSubSpaceModelDialog(
          isEdit: true,
          dialogTitle: dialogTitle,
          existingSubSpaces: _subspaces,
          onUpdate: (subspaceModels) {
            final updatedIds = subspaceModels.map((s) => s.internalId).toSet();
            final deletedSubspaces = _subspaces
                .where((s) => !updatedIds.contains(s.internalId))
                .toList();

            final List<Tag> tagsToAppendToSpace = [];

            for (var s in deletedSubspaces) {
              if (s.tags != null) {
                tagsToAppendToSpace.addAll(s.tags!);
              }
            }

            setState(() {
              _subspaces = subspaceModels;
              _tags.addAll(tagsToAppendToSpace);
            });
            if (widget.onSpaceModelUpdate != null) {
              widget.onSpaceModelUpdate!(subspaceModels, _tags);
            }
          },
        );
      },
    );
  }
}
