import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:multi_trigger_autocomplete/multi_trigger_autocomplete.dart';

import '../controls/autocomplete/mention_autocomplete_options.dart';
import '../controls/padding.dart';
import '../controls/standard_appbar.dart';
import '../globals.dart';
import '../services/connections_manager.dart';
import '../services/direct_message_service.dart';
import '../utils/active_profile_selector.dart';
import '../utils/snackbar_builder.dart';

class MessagesNewThread extends StatelessWidget {
  final receiverController = TextEditingController();
  final replyController = TextEditingController();
  final focusNode = FocusNode();

  MessagesNewThread({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: StandardAppBar.build(context, 'New Thread'),
      body: buildBody(context),
    );
  }

  Widget buildBody(BuildContext context) {
    final border = OutlineInputBorder(
      borderSide: BorderSide(
        color: Theme.of(context).colorScheme.background,
      ),
      borderRadius: BorderRadius.circular(5.0),
    );
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            MultiTriggerAutocomplete(
              textEditingController: receiverController,
              focusNode: focusNode,
              optionsAlignment: OptionsAlignment.bottomEnd,
              autocompleteTriggers: [
                AutocompleteTrigger(
                  trigger: '@',
                  optionsViewBuilder: (context, autocompleteQuery, controller) {
                    return MentionAutocompleteOptions(
                      query: autocompleteQuery.query,
                      onMentionUserTap: (user) {
                        final autocomplete =
                            MultiTriggerAutocomplete.of(context);
                        return autocomplete
                            .acceptAutocompleteOption(user.handle);
                      },
                    );
                  },
                ),
              ],
              fieldViewBuilder: (context, controller, focusNode) =>
                  TextFormField(
                focusNode: focusNode,
                maxLines: 1,
                controller: controller,
                decoration: InputDecoration(
                  labelText:
                      'Send to: (type @ and start typing name to get available accounts)',
                  alignLabelWithHint: true,
                  border: border,
                ),
              ),
            ),
            const VerticalPadding(),
            TextFormField(
              controller: replyController,
              maxLines: 8,
              decoration: InputDecoration(
                labelText: 'Reply Text',
                border: border,
              ),
            ),
            const VerticalPadding(),
            ElevatedButton(
              onPressed: () async {
                final result =
                    await getIt<ActiveProfileSelector<ConnectionsManager>>()
                        .activeEntry
                        .andThen((manager) => manager.getByHandle(
                            receiverController.text.trim().substring(1)))
                        .andThenAsync((connection) async =>
                            getIt<ActiveProfileSelector<DirectMessageService>>()
                                .activeEntry
                                .andThenAsync((dms) async => dms.newThread(
                                    connection, replyController.text)));
                result.match(onSuccess: (_) {
                  if (context.canPop()) {
                    context.pop();
                  }
                }, onError: (error) {
                  buildSnackbar(context, 'Error posting new thread: $error');
                });
              },
              child: const Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}
