import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/models/community_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/create_community/data/services/remote_create_community_service.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/create_community/presentation/bloc/create_community_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/create_community/presentation/create_community_dialog_widget.dart';
import 'package:syncrow_web/services/api/http_service.dart';

class CreateCommunityDialog extends StatelessWidget {
  final void Function(CommunityModel community) onCreateCommunity;
  final String? initialName;
  final Widget title;

  const CreateCommunityDialog({
    super.key,
    required this.onCreateCommunity,
    required this.title,
    this.initialName,
  });

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => CreateCommunityBloc(RemoteCreateCommunityService(HTTPService())),
      child: BlocListener<CreateCommunityBloc, CreateCommunityState>(
        listener: (context, state) {
          switch (state) {
            case CreateCommunityLoading():
              showDialog<void>(
                context: context,
                builder: (context) => const Center(
                  child: CircularProgressIndicator(),
                ),
              );
              break;
            case CreateCommunitySuccess(:final community):
              Navigator.of(context).pop();
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Community created successfully')),
              );
              onCreateCommunity.call(community);
              break;
            case CreateCommunityFailure():
              Navigator.of(context).pop();
              break;
            default:
              break;
          }
        },
        child: CreateCommunityDialogWidget(
          title: title,
          initialName: initialName,
        ),
      ),
    );
  }
}
