import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspaces_textfield.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class CreateSubspaceModelChipsBox extends StatelessWidget {
  const CreateSubspaceModelChipsBox({
    required this.subSpaces,
    super.key,
  });

  final List<SubspaceTemplateModel> subSpaces;

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;

    return Container(
      width: screenWidth * 0.35,
      padding: const EdgeInsets.symmetric(
        vertical: 10,
        horizontal: 16,
      ),
      decoration: BoxDecoration(
        color: ColorsManager.boxColor,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        alignment: WrapAlignment.start,
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          ...subSpaces.asMap().entries.map(
            (entry) {
              final index = entry.key;
              final subSpace = entry.value;

              final lowerName = subSpace.subspaceName.toLowerCase();

              final duplicateIndices = subSpaces
                  .asMap()
                  .entries
                  .where((e) => e.value.subspaceName.toLowerCase() == lowerName)
                  .map((e) => e.key)
                  .toList();
              final isDuplicate = duplicateIndices.length > 1 &&
                  duplicateIndices.indexOf(index) != 0;

              return SubspaceChip(
                subSpace: subSpace,
                isDuplicate: isDuplicate,
                onDeleted: () => context.read<SubSpaceModelBloc>().add(
                      RemoveSubSpaceModel(subSpace),
                    ),
              );
            },
          ),
          SubspacesTextfield(
            hintText: subSpaces.isEmpty ? 'Please enter the name' : null,
          ),
        ],
      ),
    );
  }
}
