import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_state.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class CreateSubSpaceDialog extends StatefulWidget {
  final String dialogTitle;
  final List<SubspaceModel>? existingSubSpaces;
  final String? spaceName;
  final List<ProductModel>? products;
  final void Function(List<SubspaceModel>?)? onSave;

  const CreateSubSpaceDialog({
    required this.dialogTitle,
    required this.spaceName,
    required this.products,
    required this.onSave,
    this.existingSubSpaces,
    super.key,
  });

  @override
  State<CreateSubSpaceDialog> createState() => _CreateSubSpaceDialogState();
}

class _CreateSubSpaceDialogState extends State<CreateSubSpaceDialog> {
  late final TextEditingController _subspaceNameController;

  @override
  void initState() {
    _subspaceNameController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _subspaceNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) {
        final bloc = SubSpaceBloc();
        if (widget.existingSubSpaces != null) {
          for (final subSpace in widget.existingSubSpaces ?? []) {
            bloc.add(AddSubSpace(subSpace));
          }
        }
        return bloc;
      },
      child: Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        child: BlocBuilder<SubSpaceBloc, SubSpaceState>(
          builder: (context, state) {
            return Container(
              width: context.screenWidth * 0.35,
              color: ColorsManager.whiteColors,
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    widget.dialogTitle,
                    style: context.textTheme.headlineLarge?.copyWith(
                      color: ColorsManager.blackColor,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Container(
                    width: context.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: [
                        ...state.subSpaces.asMap().entries.map(
                          (entry) {
                            final index = entry.key;
                            final subSpace = entry.value;

                            final lowerName = subSpace.subspaceName.toLowerCase();

                            final duplicateIndices = state.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: SubspaceTemplateModel(
                                subspaceName: entry.value.subspaceName,
                                disabled: entry.value.disabled,
                              ),
                              isDuplicate: isDuplicate,
                              onDeleted: () => context.read<SubSpaceBloc>().add(
                                    RemoveSubSpace(subSpace),
                                  ),
                            );
                          },
                        ),
                        SizedBox(
                          width: 200,
                          child: TextField(
                            controller: _subspaceNameController,
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: state.subSpaces.isEmpty
                                  ? 'Please enter the name'
                                  : null,
                              hintStyle: context.textTheme.bodySmall?.copyWith(
                                color: ColorsManager.lightGrayColor,
                              ),
                            ),
                            onSubmitted: (value) {
                              final trimmedValue = value.trim();
                              if (trimmedValue.isNotEmpty) {
                                context.read<SubSpaceBloc>().add(
                                      AddSubSpace(
                                        SubspaceModel(
                                          subspaceName: trimmedValue,
                                          disabled: false,
                                        ),
                                      ),
                                    );
                                _subspaceNameController.clear();
                              }
                            },
                            style: context.textTheme.bodyMedium,
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (state.errorMessage.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: Text(
                        state.errorMessage,
                        style: context.textTheme.bodySmall?.copyWith(
                          color: ColorsManager.warningRed,
                        ),
                      ),
                    ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: CancelButton(
                          label: 'Cancel',
                          onPressed: () async {
                            Navigator.of(context).pop();
                          },
                        ),
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: DefaultButton(
                          onPressed: state.errorMessage.isEmpty
                              ? () {
                                  final subSpacesBloc = context.read<SubSpaceBloc>();
                                  final subSpaces = subSpacesBloc.state.subSpaces;
                                  widget.onSave?.call(subSpaces);
                                  Navigator.of(context).pop();
                                }
                              : null,
                          backgroundColor: ColorsManager.secondaryColor,
                          borderRadius: 10,
                          foregroundColor: state.errorMessage.isNotEmpty
                              ? ColorsManager.whiteColorsWithOpacity
                              : ColorsManager.whiteColors,
                          child: const Text('OK'),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
