import 'package:flutter/cupertino.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/sc_edit_room_info_res.dart';

import 'package:yumi/shared/business_logic/models/res/my_room_res.dart';
import 'package:yumi/shared/business_logic/models/res/sc_room_contribute_level_res.dart';

class SocialChatRoomManager extends ChangeNotifier {
  MyRoomRes? myRoom;
  SCRoomContributeLevelRes? roomContributeLevelRes;
  bool isMyRoomLoading = false;
  bool hasLoadedMyRoom = false;

  Future<void> fetchMyRoomData() async {
    if (isMyRoomLoading) {
      return;
    }
    isMyRoomLoading = true;
    if (!hasLoadedMyRoom) {
      myRoom = null;
    }
    notifyListeners();
    try {
      myRoom = await SCAccountRepository().myProfile();
    } catch (_) {
      if (!hasLoadedMyRoom) {
        myRoom = null;
      }
    } finally {
      isMyRoomLoading = false;
      hasLoadedMyRoom = true;
      notifyListeners();
    }
  }

  void updateMyRoomInfo(SCEditRoomInfoRes roomInfo) {
    if (myRoom != null && myRoom!.id == roomInfo.id) {
      if ((roomInfo.roomCover ?? "").trim().isNotEmpty) {
        myRoom?.setRoomCover = roomInfo.roomCover!;
      }
      if (roomInfo.roomName != null) {
        myRoom?.setRoomName = roomInfo.roomName!;
      }
      if (roomInfo.roomDesc != null) {
        myRoom?.setRoomDesc = roomInfo.roomDesc!;
      }
      notifyListeners();
    }
  }

  void createNewRoom(BuildContext context, {String? customName}) async {
    SCLoadingManager.show(context: context);
    // 差异化：添加自定义名称参数（暂未使用，为未来扩展预留）
    if (customName != null) {
      // TODO: 实现自定义房间名称
      debugPrint('创建房间使用自定义名称: $customName');
    }
    await SCAccountRepository().createRoom();
    myRoom = await SCAccountRepository().myProfile();
    hasLoadedMyRoom = true;
    isMyRoomLoading = false;
    if (!context.mounted) {
      notifyListeners();
      SCLoadingManager.hide();
      return;
    }
    SCTts.show(SCAppLocalizations.of(context)!.createRoomSuccsess);
    notifyListeners();
    SCLoadingManager.hide();
  }

  void fetchContributionLevelData(String roomId, {bool forceRefresh = false}) {
    if (forceRefresh) {
      roomContributeLevelRes = null;
    }
    SCChatRoomRepository().roomContributionActivity(roomId).then((value) {
      roomContributeLevelRes = value;
      notifyListeners();
    });
  }
}
