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/repositories/sc_user_repository_impl.dart';
import 'package:provider/provider.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/sc_page_list.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/widgets/room/room_live_audio_indicator.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/shared/business_logic/models/res/follow_room_res.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import '../mine/sc_home_mine_skeleton.dart';

///历史房间
class SCRoomHistoryPage extends SCPageList {
  const SCRoomHistoryPage({super.key});

  @override
  SCPageListState createState() => _SCRoomHistoryPageState();
}

class _SCRoomHistoryPageState
    extends SCPageListState<FollowRoomRes, SCRoomHistoryPage> {
  String? lastId;

  @override
  void initState() {
    super.initState();
    enablePullUp = true;
    backgroundColor = Colors.transparent;
    isGridView = true;
    gridViewCount = 2;
    loadData(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.transparent,
      body:
          items.isEmpty && isLoading
              ? const SCHomeSkeletonShimmer(
                builder: _buildHistorySkeletonContent,
              )
              : buildList(context),
    );
  }

  static Widget _buildHistorySkeletonContent(
    BuildContext context,
    double progress,
  ) {
    return buildHomeRoomGridSkeleton(progress);
  }

  @override
  Widget buildItem(FollowRoomRes roomRes) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 5.w, vertical: 5.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.w),
          color: Colors.transparent,
        ),
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Container(
              padding: EdgeInsets.all(3.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("sc_images/index/sc_icon_room_bord.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child: netImage(
                url: resolveRoomCoverUrl(
                  roomRes.roomProfile?.id,
                  roomRes.roomProfile?.roomCover,
                ),
                defaultImg: kRoomCoverDefaultImg,
                borderRadius: BorderRadius.circular(12.w),
                width: 200.w,
                height: 200.w,
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(vertical: 6.w),
              margin: EdgeInsets.symmetric(horizontal: 1.w),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(
                    "sc_images/index/sc_icon_index_room_brd.png",
                  ),
                  fit: BoxFit.fill,
                ),
              ),
              child: Row(
                children: [
                  SizedBox(width: 10.w),
                  Consumer<SCAppGeneralManager>(
                    builder: (_, provider, __) {
                      return netImage(
                        url:
                            "${provider.findCountryByName(roomRes.roomProfile?.countryName ?? "")?.nationalFlag}",
                        width: 20.w,
                        height: 13.w,
                        borderRadius: BorderRadius.circular(2.w),
                      );
                    },
                  ),
                  SizedBox(width: 5.w),
                  Expanded(
                    child: SizedBox(
                      height: 17.w,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Transform.translate(
                          offset: Offset(0, -0.6.w),
                          child: text(
                            roomRes.roomProfile?.roomName ?? "",
                            fontSize: 13.sp,
                            textColor: Color(0xffffffff),
                            fontWeight: FontWeight.w400,
                            lineHeight: 1,
                          ),
                        ),
                      ),

                      // (roomRes.roomProfile?.roomName?.length ?? 0) > 10
                      //     ? Marquee(
                      //   text: roomRes.roomProfile?.roomName ?? "",
                      //   style: TextStyle(
                      //     fontSize: 15.sp,
                      //     color: Color(0xffffffff),
                      //     fontWeight: FontWeight.w400,
                      //     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(
                      //   roomRes.roomProfile?.roomName ?? "",
                      //   maxLines: 1,
                      //   overflow: TextOverflow.ellipsis,
                      //   style: TextStyle(
                      //     fontSize: 15.sp,
                      //     color: Color(0xffffffff),
                      //     fontWeight: FontWeight.w400,
                      //     decoration: TextDecoration.none,
                      //   ),
                      // ),
                    ),
                  ),
                  SizedBox(width: 5.w),
                  (roomRes
                              .roomProfile
                              ?.extValues
                              ?.roomSetting
                              ?.password
                              ?.isEmpty ??
                          false)
                      ? SCRoomLiveAudioIndicator(width: 14.w, height: 14.w)
                      : Image.asset(
                        "sc_images/index/sc_icon_room_suo.png",
                        width: 20.w,
                        height: 20.w,
                      ),
                  (roomRes
                              .roomProfile
                              ?.extValues
                              ?.roomSetting
                              ?.password
                              ?.isEmpty ??
                          false)
                      ? SizedBox(width: 3.w)
                      : Container(height: 10.w),
                  (roomRes
                              .roomProfile
                              ?.extValues
                              ?.roomSetting
                              ?.password
                              ?.isEmpty ??
                          false)
                      ? text(
                        roomRes.roomProfile?.extValues?.memberQuantity ?? "0",
                        fontSize: 10.sp,
                        lineHeight: 1,
                      )
                      : Container(height: 10.w),
                  SizedBox(width: 10.w),
                ],
              ),
            ),
            getRoomCoverHeaddress(roomRes).isNotEmpty
                ? Transform.translate(
                  offset: Offset(0, -5.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: 25.w,
                    height: 25.w,
                    borderRadius: BorderRadius.circular(4.w),
                  ),
                )
                : Container(),
          ],
        ),
      ),
      onTap: () {
        Provider.of<RtcProvider>(
          context,
          listen: false,
        ).joinVoiceRoomSession(context, roomRes.roomProfile?.id ?? "");
      },
    );
  }

  @override
  empty() {
    List<Widget> list = [];
    list.add(SizedBox(height: height(30)));
    list.add(
      Image.asset(
        'sc_images/general/sc_icon_loading.png',
        width: 120.w,
        height: 120.w,
      ),
    );
    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,
    );
  }

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

  ///加载数据
  @override
  loadPage({
    required int page,
    required Function(List<FollowRoomRes>) onSuccess,
    Function? onErr,
  }) async {
    if (page == 1) {
      lastId = null;
    }
    try {
      var roomList = await SCAccountRepository().trace(lastId: lastId);
      if (roomList.isNotEmpty) {
        lastId = roomList.last.id;
      }
      onSuccess(roomList);
    } catch (e) {
      if (onErr != null) {
        onErr();
      }
    }
  }
}
