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/ui_kit/components/text/sc_text.dart';
import 'package:marquee/marquee.dart';
import 'package:provider/provider.dart';
import '../../../../services/general/sc_app_general_manager.dart';
import '../../../../services/audio/rtc_manager.dart';
import '../../../../services/room/rc_room_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';
import 'sc_home_mine_skeleton.dart';

class SCHomeMinePage extends StatefulWidget {
  const SCHomeMinePage({super.key});

  @override
  State<SCHomeMinePage> createState() => _HomeMinePageState();
}

class _HomeMinePageState extends State<SCHomeMinePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<Widget> _pages = const [SCRoomHistoryPage(), SCRoomFollowPage()];
  final List<Widget> _tabs = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    Provider.of<SocialChatRoomManager>(
      context,
      listen: false,
    ).fetchMyRoomData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @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: [
        Consumer<SocialChatRoomManager>(
          builder: (_, provider, __) {
            if (provider.isMyRoomLoading && provider.myRoom == null) {
              return const SCHomeSkeletonShimmer(
                builder: _buildMineRoomSkeletonContent,
              );
            }
            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,
          ),
        ),
      ],
    );
  }

  static Widget _buildMineRoomSkeletonContent(
    BuildContext context,
    double progress,
  ) {
    return buildHomeMyRoomSkeleton(progress);
  }

  Widget _buildMyRoom(SocialChatRoomManager provider) {
    return provider.myRoom != null
        ? GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Row(
            children: [
              SizedBox(width: 10.w),
              netImage(
                url: resolveRoomCoverUrl(
                  provider.myRoom?.id,
                  provider.myRoom?.roomCover,
                ),
                defaultImg: kRoomCoverDefaultImg,
                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);
          },
        );
  }
}
