import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../api/marianumcloud/talk/room/get_room_response.dart';
import '../../../../routing/app_routes.dart';
import '../../../../state/app/modules/chat_list/bloc/chat_list_bloc.dart';
import '../../../../widget/confirm_dialog.dart';
import '../../../../widget/demo_restricted.dart';

/// Opens an existing 1:1 chat with [actorId] or, after confirmation, creates
/// one. Shared between the group-message context menu and the reactions
/// overview (per-participant chat shortcut).
void openOrCreateDirectChat(
  BuildContext context, {
  required String actorId,
  required String actorDisplayName,
}) {
  if (guardDemoAction(context)) return;
  final chatListBloc = context.read<ChatListBloc>();

  GetRoomResponseObject? findExisting() {
    final rooms = chatListBloc.state.data?.rooms;
    if (rooms == null) return null;
    for (final room in rooms.data) {
      if (room.type == GetRoomResponseObjectConversationType.oneToOne &&
          room.name == actorId) {
        return room;
      }
    }
    return null;
  }

  void switchToChat(String token) {
    // Pop the previous ChatView first — otherwise it stays in the
    // back-stack with a now-mismatched currentToken and renders empty
    // on back-swipe. Stop at popups so an open dialog stays alive.
    Navigator.of(
      context,
    ).popUntil((route) => route.isFirst || route is PopupRoute);
    AppRoutes.openChatByToken(context, token);
  }

  final existing = findExisting();
  if (existing != null) {
    switchToChat(existing.token);
    return;
  }

  ConfirmDialog(
    title: 'Privatchat starten?',
    content:
        'Es existiert noch kein Privatchat mit $actorDisplayName. '
        'Soll einer erstellt werden?',
    confirmButton: 'Erstellen',
    onConfirmAsync: () async {
      // The create call returns the new room's token directly, so we open it
      // without racing the (asynchronously updated) chat-list state.
      final token = await chatListBloc.createDirectChat(actorId);
      if (context.mounted && token != null) {
        switchToChat(token);
      }
    },
  ).asDialog(context);
}
