import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:marquee/marquee.dart';
import 'package:provider/provider.dart';
import '../../../../app/config/business_logic_strategy.dart';
import '../../../../app/constants/sc_global_config.dart';
import '../../../../shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import '../../../../shared/business_logic/models/res/follow_room_res.dart';
import '../../../../services/general/sc_app_general_manager.dart';
import '../../../../services/room/rc_room_manager.dart';
import '../../../../services/audio/rtc_manager.dart';
import '../../../../ui_kit/components/sc_compontent.dart';
import '../../../../ui_kit/theme/socialchat_theme.dart';
import '../follow/sc_room_follow_page.dart';
import '../history/sc_room_history_page.dart';

class SCHomeMinePage extends SCPageList {
  @override
  _HomeMinePageState createState() => _HomeMinePageState();
}

class _HomeMinePageState extends SCPageListState<FollowRoomRes, SCHomeMinePage>
    with SingleTickerProviderStateMixin {
  List<FollowRoomRes> historyRooms = [];
  String? lastId;

  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;
  late TabController _tabController;
  final List<Widget> _pages = [
    SCRoomHistoryPage(),
    SCRoomFollowPage(),

  ];
  bool isLoading = false;
  final List<Widget> _tabs = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    enablePullUp = true;
    backgroundColor = Colors.transparent;
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    _tabs.clear();
    _tabs.add(Tab(text: SCAppLocalizations.of(context)!.recent));
    _tabs.add(Tab(text: SCAppLocalizations.of(context)!.followed));
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            SizedBox(width: 15.w),
            text(
              SCAppLocalizations.of(context)!.myRoom,
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
              textColor: Colors.white,
            ),
          ],
        ),
        SizedBox(height: 5.w),
        Consumer<SocialChatRoomManager>(
          builder: (_, provider, __) {
            return Container(
              margin: EdgeInsets.symmetric(horizontal: 12.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    provider.myRoom == null
                        ? "sc_images/index/sc_icon_my_room_no_bg.png"
                        : "sc_images/index/sc_icon_my_room_has_bg.png",
                  ),
                  fit: BoxFit.fill,
                ),
              ),
              width: ScreenUtil().screenWidth,
              height: 85.w,
              child: _buildMyRoom(provider),
            );
          },
        ),
        SizedBox(height: 5.w),
        Row(
          children: [
            SizedBox(width: 5.w),
            TabBar(
              tabAlignment: TabAlignment.start,
              labelPadding: EdgeInsets.symmetric(horizontal: 12.w),
              labelColor: SocialChatTheme.primaryLight,
              isScrollable: true,
              indicator: BoxDecoration(),
              unselectedLabelColor: Colors.white,
              labelStyle: TextStyle(
                fontSize: 15.sp,
                fontFamily: 'MyCustomFont',
                fontWeight: FontWeight.w600,
              ),
              unselectedLabelStyle: TextStyle(
                fontSize: 13.sp,
                fontFamily: 'MyCustomFont',
                fontWeight: FontWeight.w500,
              ),
              indicatorColor: Colors.transparent,
              dividerColor: Colors.transparent,
              controller: _tabController,
              tabs: _tabs,
            ),
          ],
        ),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            physics: NeverScrollableScrollPhysics(),
            children: _pages,
          ),
        )
      ],
    );
  }

  _buildMyRoom(SocialChatRoomManager provider) {
    return provider.myRoom != null
        ? GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Row(
            children: [
              SizedBox(width: 10.w),
              netImage(
                url: provider.myRoom?.roomCover ?? "",
                borderRadius: BorderRadius.all(Radius.circular(8.w)),
                width: 70.w,
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Stack(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 6.w),
                        Row(
                          children: [
                            netImage(
                              url:
                                  Provider.of<SCAppGeneralManager>(
                                        context,
                                        listen: false,
                                      )
                                      .findCountryByName(
                                        AccountStorage()
                                                .getCurrentUser()
                                                ?.userProfile
                                                ?.countryName ??
                                            "",
                                      )
                                      ?.nationalFlag ??
                                  "",
                              borderRadius: BorderRadius.all(
                                Radius.circular(3.w),
                              ),
                              width: 19.w,
                              height: 14.w,
                            ),
                            SizedBox(width: 3.w),
                            Container(
                              constraints: BoxConstraints(
                                maxWidth: 200.w,
                                maxHeight: 24.w,
                              ),
                              child:
                                  (provider.myRoom?.roomName?.length ?? 0) > 18
                                      ? Marquee(
                                        text: provider.myRoom?.roomName ?? "",
                                        style: TextStyle(
                                          fontSize: 16.sp,
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                          decoration: TextDecoration.none,
                                        ),
                                        scrollAxis: Axis.horizontal,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        blankSpace: 40.0,
                                        velocity: 40.0,
                                        pauseAfterRound: Duration(seconds: 1),
                                        accelerationDuration: Duration(
                                          seconds: 1,
                                        ),
                                        accelerationCurve: Curves.easeOut,
                                        decelerationDuration: Duration(
                                          milliseconds: 500,
                                        ),
                                        decelerationCurve: Curves.easeOut,
                                      )
                                      : Text(
                                        provider.myRoom?.roomName ?? "",
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: 16.sp,
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                          decoration: TextDecoration.none,
                                        ),
                                      ),
                            ),
                          ],
                        ),
                        text(
                          provider.myRoom?.roomDesc ?? "",
                          fontSize: 14.sp,
                          textColor: Colors.white,
                        ),
                        text(
                          "ID:${provider.myRoom?.roomAccount}",
                          fontSize: 12.sp,
                          textColor: Colors.white,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(width: 12.w),
            ],
          ),
          onTap: () {
            String roomId =
                Provider.of<SocialChatRoomManager>(
                  context,
                  listen: false,
                ).myRoom?.id ??
                "";
            Provider.of<RealTimeCommunicationManager>(
              context,
              listen: false,
            ).joinVoiceRoomSession(context, roomId);
          },
        )
        : GestureDetector(
          child: Row(
            children: [
              SizedBox(width: 10.w),
              Image.asset(
                "sc_images/index/sc_icon_index_creat_room_tag.png",
                height: 70.w,
                width: 70.w,
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    text(
                      SCAppLocalizations.of(context)!.crateMyRoom,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.bold,
                      textColor: Colors.white,
                    ),
                    text(
                      SCAppLocalizations.of(context)!.startYourBrandNewJourney,
                      fontSize: 12.sp,
                      textColor: Colors.white,
                    ),
                  ],
                ),
              ),
              Image.asset(
                "sc_images/index/sc_icon_my_room_tag2.png",
                height: 25.w,
                width: 25.w,
              ),
              SizedBox(width: 10.w),
              Icon(
                Icons.chevron_right_outlined,
                color: Colors.white,
                size: 20.w,
              ),
              SizedBox(width: 15.w),
            ],
          ),
          onTap: () {
            provider.createNewRoom(context);
          },
        );
  }

  void _loadOtherData() {
    SCLoadingManager.show();
    Provider.of<SocialChatRoomManager>(
      context,
      listen: false,
    ).fetchMyRoomData();
    SCAccountRepository()
        .trace()
        .then((res) {
          historyRooms = res;
          SCLoadingManager.hide();
          setState(() {});
        })
        .catchError((_) {
          SCLoadingManager.hide();
        });
  }

  _buildHistoryRoomItem(FollowRoomRes roomRes) {
    return GestureDetector(
      child: SizedBox(
        width: 70.w,
        height: 70.w,
        child: Stack(
          children: [
            netImage(
              url: roomRes.roomProfile?.roomCover ?? "",
              width: 70.w,
              height: 70.w,
              fit: BoxFit.cover,
              borderRadius: BorderRadius.circular(8.w),
            ),
            getRoomCoverHeaddress(roomRes).isNotEmpty
                ? Transform.translate(
                  offset: Offset(0, -2.w),
                  child: Transform.scale(
                    scaleX: 1.1,
                    scaleY: 1.12,
                    child: Image.asset(getRoomCoverHeaddress(roomRes)),
                  ),
                )
                : Container(),
            (roomRes.roomProfile?.roomGameIcon?.isNotEmpty ?? false)
                ? PositionedDirectional(
                  top: 8.w,
                  end: 8.w,
                  child: netImage(
                    url: roomRes.roomProfile?.roomGameIcon ?? "",
                    width: 15.w,
                    height: 15.w,
                    borderRadius: BorderRadius.circular(4.w),
                  ),
                )
                : Container(),
            PositionedDirectional(
              top: 3.w,
              end: 5.w,
              child:
                  (roomRes
                              .roomProfile
                              ?.extValues
                              ?.roomSetting
                              ?.password
                              ?.isNotEmpty ??
                          false)
                      ? Image.asset(
                        "sc_images/index/sc_icon_room_suo.png",
                        width: 16.w,
                        height: 16.w,
                      )
                      : Container(),
            ),
          ],
        ),
      ),
      onTap: () {
        Provider.of<RtcProvider>(
          context,
          listen: false,
        ).joinVoiceRoomSession(context, roomRes.roomProfile?.id ?? "");
      },
    );
  }

  @override
  Widget buildItem(FollowRoomRes res) {
    return SCDebounceWidget(
      child: SizedBox(
        height: 105.w,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(13.w),
                border: Border.all(
                  color: _strategy.getExploreRoomBorderColor(),
                  width: _strategy.getExploreRoomBorderWidth().w,
                ),
              ),
              margin: EdgeInsetsDirectional.symmetric(
                horizontal: 10.w,
                vertical: 3.w,
              ),
            ),
            Row(
              children: [
                SizedBox(width: 20.w),
                netImage(
                  url: res.roomProfile?.roomCover ?? "",
                  fit: BoxFit.cover,
                  borderRadius: BorderRadius.all(Radius.circular(12.w)),
                  width: 85.w,
                  height: 85.w,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 15.w),
                    Row(
                      children: [
                        SizedBox(width: 8.w),
                        Consumer<SCAppGeneralManager>(
                          builder: (_, provider, __) {
                            return netImage(
                              url:
                                  "${provider.findCountryByName(res.roomProfile?.countryName ?? "")?.nationalFlag}",
                              width: 25.w,
                              height: 15.w,
                              borderRadius: BorderRadius.all(
                                Radius.circular(3.w),
                              ),
                            );
                          },
                        ),
                        SizedBox(width: 5.w),
                        Container(
                          constraints: BoxConstraints(
                            maxHeight: 21.w,
                            maxWidth: 150.w,
                          ),
                          child:
                              (res.roomProfile?.roomName?.length ?? 0) >
                                      _strategy
                                          .getExploreRoomNameMarqueeThreshold()
                                  ? Marquee(
                                    text: res.roomProfile?.roomName ?? "",
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                    scrollAxis: Axis.horizontal,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    blankSpace: 20.0,
                                    velocity: 40.0,
                                    pauseAfterRound: Duration(seconds: 1),
                                    accelerationDuration: Duration(seconds: 1),
                                    accelerationCurve: Curves.easeOut,
                                    decelerationDuration: Duration(
                                      milliseconds: 500,
                                    ),
                                    decelerationCurve: Curves.easeOut,
                                  )
                                  : Text(
                                    res.roomProfile?.roomName ?? "",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                        ),
                      ],
                    ),
                    SizedBox(height: 3.w),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(width: 8.w),
                        text(
                          "ID:${res.roomProfile?.roomAccount}",
                          fontWeight: FontWeight.w600,
                          textColor: Colors.black,
                          fontSize: 15.sp,
                        ),
                      ],
                    ),
                    SizedBox(height: 3.w),
                    Row(
                      children: [
                        SizedBox(width: 8.w),
                        Image.asset(
                          "sc_images/msg/sc_icon_message_activity.png",
                          height: 25.w,
                          width: 25.w,
                        ),
                        SizedBox(width: 4.w),
                        Container(
                          constraints: BoxConstraints(
                            maxHeight: 21.w,
                            maxWidth: 170.w,
                          ),
                          child:
                              (res.roomProfile?.roomDesc?.length ?? 0) >
                                      _strategy
                                          .getExploreRoomDescMarqueeThreshold()
                                  ? Marquee(
                                    text: res.roomProfile?.roomDesc ?? "",
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      color: Colors.black,
                                      decoration: TextDecoration.none,
                                    ),
                                    scrollAxis: Axis.horizontal,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    blankSpace: 20.0,
                                    velocity: 40.0,
                                    pauseAfterRound: Duration(seconds: 1),
                                    accelerationDuration: Duration(seconds: 1),
                                    accelerationCurve: Curves.easeOut,
                                    decelerationDuration: Duration(
                                      milliseconds: 500,
                                    ),
                                    decelerationCurve: Curves.easeOut,
                                  )
                                  : Text(
                                    res.roomProfile?.roomDesc ?? "",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontSize: 15.sp,
                                      color: Colors.black,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
      onTap: () {
        Provider.of<RtcProvider>(
          context,
          listen: false,
        ).joinVoiceRoomSession(context, res.roomProfile?.id ?? "");
      },
    );
  }

  @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<FollowRoomRes>) onSuccess,
    Function? onErr,
  }) async {
    _loadOtherData();
    if (page == 1) {
      lastId = null;
    }
    try {
      var roomList = await SCAccountRepository().followRoomList(lastId: lastId);
      if (roomList.isNotEmpty) {
        lastId = roomList.last.id;
      }
      onSuccess(roomList);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }

  String getRoomCoverHeaddress(FollowRoomRes roomRes) {
    return "";
  }
}
