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/space_management_v2/modules/create_community/domain/param/create_community_param.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_name_text_field.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class CreateCommunityDialogWidget extends StatefulWidget {
  final String? initialName;
  final Widget title;

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

  @override
  State<CreateCommunityDialogWidget> createState() =>
      _CreateCommunityDialogWidgetState();
}

class _CreateCommunityDialogWidgetState extends State<CreateCommunityDialogWidget> {
  late final TextEditingController _nameController;

  @override
  void initState() {
    _nameController = TextEditingController(text: widget.initialName ?? '');
    super.initState();
  }

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

  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      backgroundColor: ColorsManager.transparentColor,
      child: Container(
        width: MediaQuery.of(context).size.width * 0.3,
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: ColorsManager.whiteColors,
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: ColorsManager.blackColor.withValues(alpha: 0.25),
              blurRadius: 20,
              spreadRadius: 5,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: BlocBuilder<CreateCommunityBloc, CreateCommunityState>(
              builder: (context, state) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    DefaultTextStyle(
                      style: Theme.of(context).textTheme.headlineMedium!,
                      child: widget.title,
                    ),
                    const SizedBox(height: 18),
                    CreateCommunityNameTextField(
                      nameController: _nameController,
                    ),
                    if (state case CreateCommunityFailure(:final message))
                      Padding(
                        padding: const EdgeInsets.only(top: 18),
                        child: SelectableText(
                          '* $message',
                          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                                color: Theme.of(context).colorScheme.error,
                              ),
                        ),
                      ),
                    const SizedBox(height: 24),
                    _buildActionButtons(context),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: CancelButton(
            label: 'Cancel',
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        const SizedBox(width: 16),
        _buildCreateCommunityButton(context),
      ],
    );
  }

  Widget _buildCreateCommunityButton(BuildContext context) {
    return Expanded(
      child: DefaultButton(
        onPressed: () {
          if (_formKey.currentState?.validate() ?? false) {
            _onSubmit(context);
          }
        },
        borderRadius: 10,
        foregroundColor: ColorsManager.whiteColors,
        child: const Text('OK'),
      ),
    );
  }

  void _onSubmit(BuildContext context) {
    if (_formKey.currentState?.validate() ?? false) {
      context.read<CreateCommunityBloc>().add(
            CreateCommunity(
              CreateCommunityParam(
                name: _nameController.text.trim(),
              ),
            ),
          );
    }
  }
}
