import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:provider/provider.dart';
import 'package:yumi/app/constants/sc_room_msg_type.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/business_logic/models/res/room_member_res.dart';
import 'package:yumi/services/audio/rtm_manager.dart';
import 'package:yumi/ui_kit/widgets/room/room_msg_item.dart';

import '../../../shared/data_sources/models/enum/sc_room_roles_type.dart';
import '../../../ui_kit/components/sc_compontent.dart';
import '../../../ui_kit/components/sc_debounce_widget.dart';
import '../../../ui_kit/components/sc_page_list.dart';
import '../../../ui_kit/components/sc_tts.dart';
import '../../../ui_kit/components/text/sc_text.dart';

///房间成员列表
class RoomMemberPage extends SCPageList {
  String? roomId = "";
  bool isHomeowner = false;

  RoomMemberPage({super.key, this.roomId, this.isHomeowner = false});

  @override
  _RoomMemberPageState createState() =>
      _RoomMemberPageState(roomId, isHomeowner);
}

class _RoomMemberPageState
    extends SCPageListState<List<SocialChatRoomMemberRes>, RoomMemberPage> {
  String? roomId = "";
  String? lastId;
  bool isHomeowner = false;
  List<List<SocialChatRoomMemberRes>> mList = [];
  String optTips = "";

  _RoomMemberPageState(this.roomId, this.isHomeowner);

  @override
  void initState() {
    super.initState();
    enablePullUp = false;
    enablePullDown = false;
    backgroundColor = Colors.transparent;
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    optTips = SCAppLocalizations.of(context)!.operationSuccessful;
    return SafeArea(
      child: ClipRRect(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.0),
          topRight: Radius.circular(12.0),
        ),
        child: BackdropFilter(
          filter: ui.ImageFilter.blur(sigmaX: 15, sigmaY: 15),
          child: Container(
            width: ScreenUtil().screenWidth,
            color: Color(0xff09372E).withOpacity(0.5),
            child: Column(
              children: [
                SizedBox(height: 15.w),
                text(
                  SCAppLocalizations.of(context)!.roomMember,
                  fontSize: 14.sp,
                  textColor: Colors.white,
                ),
                SizedBox(height: 10.w),
                SizedBox(height: 350.w, child: buildList(context)),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget buildItem(List<SocialChatRoomMemberRes> list) {
    return Column(
      children: [
        list.isNotEmpty ? buildTag(list.first.roles) : Container(),
        SizedBox(height: 3.w),
        Column(
          children: List.generate(list.length, (cIndex) {
            SocialChatRoomMemberRes userInfo = list[cIndex];
            return GestureDetector(
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.w),
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.w),
                  color: Color(0xffF2F2F2),
                ),
                child: Row(
                  children: [
                    head(
                      url: userInfo.userProfile?.userAvatar ?? "",
                      width: 52.w,
                      headdress:
                          userInfo.userProfile?.getHeaddress()?.sourceUrl,
                    ),
                    SizedBox(width: 3.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 240.w,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: Row(
                              children: [
                                msgRoleTag(
                                  userInfo.roles ?? "",
                                  width: 20.w,
                                  height: 20.w,
                                ),
                                SizedBox(width: 3.w),
                                socialchatNickNameText(
                                  maxWidth: 160.w,
                                  userInfo.userProfile?.userNickname ?? "",
                                  fontSize: 14.sp,
                                  textColor: Colors.black,
                                  type:
                                      userInfo.userProfile?.getVIP()?.name ??
                                      "",
                                  needScroll:
                                      (userInfo
                                              .userProfile
                                              ?.userNickname
                                              ?.characters
                                              .length ??
                                          0) >
                                      14,
                                ),
                                SizedBox(width: 3.w),
                                userInfo.userProfile?.getVIP() != null
                                    ? netImage(
                                      url:
                                          userInfo.userProfile
                                              ?.getVIP()
                                              ?.cover ??
                                          "",
                                      width: 25.w,
                                      height: 25.w,
                                    )
                                    : Container(),
                                SizedBox(width: 5.w),
                                userInfo.userProfile?.wearBadge?.isNotEmpty ??
                                        false
                                    ? SizedBox(
                                      height: 25.w,
                                      child: ListView.separated(
                                        scrollDirection: Axis.horizontal,
                                        shrinkWrap: true,
                                        itemCount:
                                            userInfo
                                                .userProfile
                                                ?.wearBadge
                                                ?.length ??
                                            0,
                                        itemBuilder: (context, index) {
                                          return netImage(
                                            width: 25.w,
                                            height: 25.w,
                                            url:
                                                userInfo
                                                    .userProfile
                                                    ?.wearBadge?[index]
                                                    .selectUrl ??
                                                "",
                                          );
                                        },
                                        separatorBuilder: (
                                          BuildContext context,
                                          int index,
                                        ) {
                                          return SizedBox(width: 5.w);
                                        },
                                      ),
                                    )
                                    : Container(),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 3.w),
                        text(
                          "ID:${userInfo.userProfile?.getID()}",
                          fontSize: 12.sp,
                          textColor: Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                      ],
                    ),
                    Spacer(),
                    userInfo.roles != SCRoomRolesType.HOMEOWNER.name &&
                            isHomeowner
                        ? SCDebounceWidget(
                          child: Image.asset(
                            "sc_images/room/sc_icon_remve_block.png",
                            width: 20.w,
                            height: 20.w,
                          ),
                          onTap: () {
                            SCChatRoomRepository()
                                .changeRoomRole(
                                  roomId ?? "",
                                  SCRoomRolesType.TOURIST.name,
                                  userInfo.userProfile?.id ?? "",
                                  AccountStorage()
                                          .getCurrentUser()
                                          ?.userProfile
                                          ?.id ??
                                      "",
                                  "OTHER_CHANGE",
                                )
                                .whenComplete(() {
                                  SCTts.show(optTips);
                                  Msg msg = Msg(
                                    groupId:
                                        Provider.of<RtcProvider>(
                                              context,
                                              listen: false,
                                            )
                                            .currenRoom
                                            ?.roomProfile
                                            ?.roomProfile
                                            ?.roomAccount,
                                    msg: 'TOURIST',
                                    toUser: userInfo.userProfile,
                                    type: SCRoomMsgType.roomRoleChange,
                                  );
                                  Provider.of<RtmProvider>(
                                    context,
                                    listen: false,
                                  ).dispatchMessage(msg, addLocal: true);
                                  Navigator.of(context).pop();
                                });
                          },
                        )
                        : Container(),
                  ],
                ),
              ),
              onTap: () {
                Navigator.of(context).pop();
                num index = Provider.of<RtcProvider>(
                  context,
                  listen: false,
                ).userOnMaiInIndex(userInfo.id ?? "");
                Provider.of<RtcProvider>(
                  context,
                  listen: false,
                ).clickSite(index, clickUser: userInfo.userProfile);
              },
            );
          }),
        ),
      ],
    );
  }

  @override
  empty() {
    List<Widget> list = [];
    list.add(SizedBox(height: height(30)));
    list.add(CupertinoActivityIndicator());
    list.add(SizedBox(height: height(15)));
    list.add(
      Text(
        SCAppLocalizations.of(context)!.noData,
        style: TextStyle(
          fontSize: sp(14),
          color: Color(0xff999999),
          fontWeight: FontWeight.w400,
          decoration: TextDecoration.none,
          height: 1,
        ),
      ),
    );
    return Column(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: list,
    );
  }

  @override
  builderDivider() {
    // return Divider(
    //   height: 1.w,
    //   color: Color(0xff3D3277).withOpacity(0.5),
    //   indent: 15.w,
    // );
    return Container(height: 8.w);
  }

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<List<SocialChatRoomMemberRes>>) onSuccess,
    Function? onErr,
  }) async {
    if (page == 1) {
      lastId = null;
      mList.clear();
      mList.add([]);
      mList.add([]);
      mList.add([]);
    }
    try {
      var userList = await SCChatRoomRepository().roomMember(
        roomId ?? "",
        lastId: lastId,
      );
      for (var user in userList) {
        if (user.roles == SCRoomRolesType.HOMEOWNER.name) {
          // mList["Homeowner"]?.add(user);
          mList[0].add(user);
        } else if (user.roles == SCRoomRolesType.ADMIN.name) {
          // mList["Administrator"]?.add(user);
          mList[1].add(user);
        } else if (user.roles == SCRoomRolesType.MEMBER.name) {
          // mList["Member"]?.add(user);
          mList[2].add(user);
        }
      }
      onSuccess(mList);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }

  Widget buildTag(String? roles) {
    if (roles == SCRoomRolesType.HOMEOWNER.name) {
      return Row(
        children: [
          SizedBox(width: 5.w),
          text(
            SCAppLocalizations.of(context)!.owner,
            fontSize: 13.sp,
            textColor: Colors.white,
          ),
          Spacer(),
        ],
      );
    } else if (roles == SCRoomRolesType.ADMIN.name) {
      return Row(
        children: [
          SizedBox(width: 5.w),
          text(
            SCAppLocalizations.of(context)!.admin,
            fontSize: 13.sp,
            textColor: Colors.white,
          ),
          Spacer(),
          // Image.asset(
          //   "images/room/sc_icon_add_user.png",
          //   width: 25.w,
          //   height: 25.w,
          // ),
          // SizedBox(width: 3.w),
        ],
      );
    } else if (roles == SCRoomRolesType.MEMBER.name) {
      return Row(
        children: [
          SizedBox(width: 5.w),
          text(
            SCAppLocalizations.of(context)!.member,
            fontSize: 13.sp,
            textColor: Colors.white,
          ),
          Spacer(),
          // Image.asset(
          //   "images/room/sc_icon_add_user.png",
          //   width: 25.w,
          //   height: 25.w,
          // ),
          // SizedBox(width: 3.w),
        ],
      );
    }
    return Container();
  }
}
