import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/controller/video_module_controller.dart';
import 'package:loopin/utils/common.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimSDKListener.dart';
import 'package:tencent_cloud_chat_sdk/enum/log_level_enum.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';

final logger = Logger();

class ImCore {
  static bool _isInitialized = false;

  static Future<void> handleLogout() async {
    final loginRes = await ImService.instance.logout();
    if (loginRes.success) {
      // 清除存储信息
      Common.logout();
      // 初始化视频
      final videoController = Get.find<VideoModuleController>();
      videoController.init();
      Get.offAllNamed(
        '/login',
        predicate: (route) {
          return route.settings.name == '/';
        },
      );
    }
  }

  static Future<bool> init({required int sdkAppId}) async {
    if (_isInitialized) return true;

    final res = await TencentImSDKPlugin.v2TIMManager.initSDK(
      sdkAppID: sdkAppId,
      loglevel: LogLevelEnum.V2TIM_LOG_ERROR,
      listener: V2TimSDKListener(
        onConnectSuccess: () {
          logger.i("IM连接成功");
        },
        onConnectFailed: (code, error) => logger.e("IM连接失败: $code $error"),
        onKickedOffline: () {
          logger.w("IM被踢下线");
          Get.snackbar(
            '提示',
            '您的帐号已在其他处登录',
            duration: Duration(seconds: 10),
            backgroundColor: Colors.red.withAlpha(230),
            colorText: Colors.white,
            icon: const Icon(Icons.error_outline, color: Colors.white),
          );
          handleLogout();
        },
        onUserSigExpired: () => logger.w("UserSig 过期"),
        onSelfInfoUpdated: (V2TimUserFullInfo info) {
          final ImUserInfoController imUserInfoController = Get.find<ImUserInfoController>();
          imUserInfoController.refreshUserInfo();
          logger.i("用户信息更新: ${info.toJson()}");
        },
      ),
    );

    if (res.code == 0) {
      _isInitialized = true;
      logger.i("IM SDK 初始化成功");

      return true;
    } else {
      logger.e("IM SDK 初始化失败: ${res.code} - ${res.desc}");
      return false;
    }
  }

  // 反向初始化
  static Future<void> unInit() async {
    if (_isInitialized) {
      final res = await TencentImSDKPlugin.v2TIMManager.unInitSDK();
      if (res.code == 0) {
        logger.i("IM SDK 已反初始化");
      } else {
        logger.e("IM SDK 反初始化失败: ${res.code} - ${res.desc}");
      }
      _isInitialized = false;
    }
  }
}
