import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';

import '../../bloc/subspace_bloc.dart';
import '../../bloc/subspace_event.dart';

class OkCancelSubSpaceWidget extends StatelessWidget {
  const OkCancelSubSpaceWidget({
    super.key,
    required this.subspaceNameController,
    required this.onSave,
    required this.errorMessage,
  });

  final TextEditingController subspaceNameController;
  final void Function(
      List<SubspaceModel>?, List<UpdateSubspaceModel> updatedSubSpaces)? onSave;
  final String errorMessage;
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: CancelButton(
            label: 'Cancel',
            onPressed: () async {
              Navigator.of(context).pop();
            },
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: DefaultButton(
            onPressed: errorMessage.isEmpty
                ? () async {
                    final trimmedValue = subspaceNameController.text.trim();

                    final subSpacesBloc = context.read<SubSpaceBloc>();
                    if (trimmedValue.isNotEmpty) {
                      subSpacesBloc.add(
                        AddSubSpace(
                          SubspaceModel(
                            subspaceName: trimmedValue,
                            disabled: false,
                          ),
                        ),
                      );
                      subspaceNameController.clear();
                    }

                    await Future.delayed(const Duration(milliseconds: 10));
                    final subSpaces = subSpacesBloc.state.subSpaces;

                    onSave?.call(
                        subSpaces, subSpacesBloc.state.updatedSubSpaceModels);

                    Navigator.of(context).pop();
                  }
                : null,
            backgroundColor: ColorsManager.secondaryColor,
            borderRadius: 10,
            foregroundColor: errorMessage.isNotEmpty
                ? ColorsManager.whiteColorsWithOpacity
                : ColorsManager.whiteColors,
            child: const Text('OK'),
          ),
        ),
      ],
    );
  }
}
