import 'package:betting/commom/utils/color_utils.dart';
import 'package:betting/commom/utils/textstyle.dart';
import 'package:betting/view/mobile/favourites_view/bottom_sheet_widget/bottom_sheet_widget.dart';
import 'package:betting/view/mobile/favourites_view/teams/switch_controller.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/matches_view/matches_view.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/news_view/news_view.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/overview_view/overview_view.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/squad_view/squad_view.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/team_info_controller.dart';
import 'package:betting/view/mobile/favourites_view/teams/team_info_view/videos_view/videos_view.dart';
import 'package:betting/view/mobile/favourites_view/widgets/toast_wiget.dart';
import 'package:betting/view/mobile/scores/football/detail_tournament/player_stats/player_stats_page.dart';
import 'package:betting/view/mobile/scores/football/detail_tournament/table_tournament/table_tournament_page.dart';
import 'package:betting/view/mobile/scores/football/detail_tournament/team_stats/team_stats_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_device_type/flutter_device_type.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class TeamsInfoView extends StatefulWidget {
  const TeamsInfoView({Key? key}) : super(key: key);

  @override
  State<TeamsInfoView> createState() => _TeamsInfoViewState();
}

class _TeamsInfoViewState extends State<TeamsInfoView> {
  final teamInfoController = Get.put(TeamInfoController());
  final switchController = Get.find<SwitchController>();

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Image.asset(
        "assets/images/background_app_betting.jpg",
        height: Get.height,
        width: Get.width,
        fit: BoxFit.cover,
      ),
      Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          automaticallyImplyLeading: false,
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(35),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      const SizedBox(width: 10,),
                      GestureDetector(
                        onTap: () {
                        Get.back();
                      },
                        child: const Icon(
                          Icons.arrow_back_ios_new_rounded,
                          size: 20,
                          color: Colors.white54,
                        ),
                      ),
                      SizedBox(width: 8.w,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            width: 8,
                          ),
                          CachedNetworkImage(
                            imageUrl: teamInfoController.itemTeam.value.logo ?? 'https://upload.wikimedia.org/wikipedia/vi/thumb/5/5c/Chelsea_crest.svg/1200px-Chelsea_crest.svg.png',
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            placeholder: (context, url) => const CupertinoActivityIndicator(),
                            memCacheHeight: 150,
                            memCacheWidth: 150,
                            errorWidget: (context, url, error) =>
                                Image.network( "https://files.lms.xteldev.com/files/n1/static/img",),
                            width: 25,
                            height: 25,
                          ),
                          SizedBox(
                            width: 15.w,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: !Device.get().isTablet? 225.w : null,
                                child: Text(teamInfoController.itemTeam.value.name!,
                                  softWrap: false,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyleUtils.sizeText14Weight400()!
                                      .copyWith(color: Colors.white),
                                ),
                              ),
                              SizedBox(height: 5.h,),
                              Text(
                                teamInfoController.itemTeam.value.country!.name!,
                                style: TextStyleUtils.sizeText12Weight400()!
                                    .copyWith(color: Colors.white54),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                  Obx(() => Theme(
                      data: Theme.of(context).copyWith(
                        dividerTheme: const DividerThemeData(
                          color: Colors.grey,
                        ),
                        splashColor: Colors.transparent,
                        iconTheme: const IconThemeData(color: Colors.white),
                        textTheme: const TextTheme().apply(bodyColor: Colors.white),
                      ),
                      child: teamInfoController.itemTeam.value.favourite == false
                          ? IconButton(
                              onPressed: () {
                                teamInfoController.itemTeam.value.favourite = true;

                                showModalBottomSheet(
                                  backgroundColor: Colors.transparent,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return BottomSheetWidget();
                                  },
                                );
                              },
                              icon: const Icon(Icons.star_outline_rounded),
                            )
                          : PopupMenuButton<int>(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              constraints: const BoxConstraints.expand(
                                  width: 265, height: 195),
                              icon: const Icon(
                                Icons.star_rounded,
                                color: ColorUtils.PRIMARY_COLOR,
                              ),
                              color: Colors.black,
                              onSelected: (item) {
                                if(item == 0) {
                                  teamInfoController.itemTeam.value.favourite = !teamInfoController.itemTeam.value.favourite!;

                                  if(teamInfoController.itemTeam.value.favourite == false) {
                                    teamInfoController.teamController
                                        .deleteFavouriteTeam(
                                        teamInfoController.itemTeam.value.id!);
                                  }

                                  CustomToast().showToast(context, 'Team', false);
                                } else {
                                  teamInfoController.popupItem[item]['isAllowNotifications'] = !teamInfoController.popupItem[item]['isAllowNotifications'];

                                  if(teamInfoController.popupItem[item]['isAllowNotifications'] == true) {
                                    teamInfoController.popupItem[item]['icon'] = Icons.notifications_off_outlined;
                                    teamInfoController.popupItem[item]['nameItem'] = teamInfoController.popupItem[item]['nameItem'].replaceAll("Unmute", "Mute");
                                  } else {
                                    teamInfoController.popupItem[item]['icon'] = Icons.notifications_outlined;
                                    teamInfoController.popupItem[item]['nameItem'] = teamInfoController.popupItem[item]['nameItem'].replaceAll("Mute", "Unmute");
                                  }
                                }
                              },
                              itemBuilder: (context) {
                                return List<PopupMenuEntry<int>>.generate(
                                  teamInfoController.popupItem.length * 2 - 1,
                                  (index) {
                                    if (index.isOdd) {
                                      return const PopupMenuDivider();
                                    } else {
                                      final itemIndex = index ~/ 2;
                                      final item = teamInfoController.popupItem[itemIndex];

                                      return PopupMenuItem<int>(
                                        value: item['id']!,
                                        child: Row(
                                          children: [
                                            Icon(
                                              item['icon']!,
                                              color: Colors.white,
                                            ),
                                            const SizedBox(
                                              width: 10,
                                            ),
                                            Text(item['nameItem']!,
                                              style: const TextStyle(
                                                color: Colors.white,
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                                    }
                                  },
                                );
                              },
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        body: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: TabBar(
                  controller: teamInfoController.tabController,
                  labelColor: ColorUtils.PRIMARY_COLOR,
                  isScrollable: true,
                  indicatorColor: Colors.transparent,
                  unselectedLabelColor: Colors.white54,
                  labelStyle: TextStyle(fontSize: 12.sp),
                  tabs: List<Widget>.generate(
                    teamInfoController.tabTitles.length,
                    (index) => Tab(
                      text: teamInfoController.tabTitles[index],
                    ),
                  ),
                ),
              ),
            ];
          },
          body: TabBarView(
            physics: const BouncingScrollPhysics(),
            controller: teamInfoController.tabController,
            children: [
              OverviewView(),
              MatchesView(),
              TableTournamentPage(),
              NewsView(),
              SquadView(),
              VideosView(),
              TournamentPlayerStatsPage(),
              TournamentTeamStatsPage(),
            ],
          ),
        ),
      ),
    ]);
  }
}
