import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/utils/parse_message_summary.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';

class NotificationBanner {
  static void show(V2TimMessage msg) {
    final nickname = msg.nameCard ?? msg.nickName ?? msg.senderProfile?.nickName ?? msg.sender ?? '未知用户';
    final avatar = msg.faceUrl ?? msg.senderProfile?.faceUrl ?? '';
    final text = parseMessageSummary(msg);

    Get.snackbar(
      nickname,
      text,
      duration: const Duration(seconds: 3),
      snackPosition: SnackPosition.TOP,
      margin: const EdgeInsets.all(12),
      backgroundColor: Get.theme.cardColor,
      colorText: Get.theme.textTheme.bodyLarge?.color,
      icon: avatar.isNotEmpty
          ? CircleAvatar(
              backgroundImage: NetworkImage(avatar),
              radius: 16,
            )
          : null,
      onTap: (_) async {
        // 点击后立刻关闭
        Get.closeCurrentSnackbar();
        String? conversationID;
        if (msg.groupID != null && msg.groupID!.isNotEmpty) {
          conversationID = 'group_${msg.groupID}';
        } else if (msg.userID != null && msg.userID!.isNotEmpty) {
          conversationID = 'c2c_${msg.userID}';
        }
        final cRes = await ImService.instance.getConversation(conversationID: conversationID!);
        if (cRes.success) {
          if (msg.userID != null) {
            // 单聊消息
            Get.toNamed('/chat', arguments: cRes.data);
          } else if (msg.groupID != null) {
            Get.toNamed('/chat', arguments: cRes.data);
          }
        } else {
          // 异常
          MyDialog.toast(cRes.desc, icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
        }
      },
    );
  }

  /// 被关注通知
  static void foucs(V2TimUserFullInfo msg) {
    final nickname = msg.nickName ?? '未知用户';
    final avatar = msg.faceUrl ?? '';
    final text = '$nickname：关注了你';

    Get.snackbar(
      '新的关注',
      text,
      duration: const Duration(seconds: 5),
      snackPosition: SnackPosition.TOP,
      margin: const EdgeInsets.all(12),
      backgroundColor: Get.theme.cardColor,
      colorText: Get.theme.textTheme.bodyLarge?.color,
      icon: avatar.isNotEmpty
          ? CircleAvatar(
              backgroundImage: NetworkImage(avatar),
              radius: 16,
            )
          : null,
      onTap: (_) async {
        // 点击后立刻关闭
        Get.closeCurrentSnackbar();
        // 跳转到新关注我的页面
      },
    );
  }
}
