import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/common/widgets/toast.dart';
import 'package:taafee_mobile/core/local_storage/local_storage.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
import 'package:taafee_mobile/features/account/presentation_layer/screens/account.dart';
import 'package:taafee_mobile/features/auth/business_logic_layer/auth_controller.dart';
import 'package:taafee_mobile/features/chat/data_layer/model/message.dart';
import 'package:taafee_mobile/features/chat/presentation_layer/screens/chat.dart';
import 'package:taafee_mobile/features/favorite/business_logic_layer/favorite_controller.dart';
import 'package:taafee_mobile/features/favorite/presentation_layer/screens/favorite.dart';
import 'package:taafee_mobile/features/home/business_logic_layer/home_controller.dart';
import '../../../../common/const/const.dart';
import '../../../auth/data_layer/model/user.dart';
// import '../../../card/data_layer/model/card_model.dart';
// import '../../../card/data_layer/source/card_service.dart';
import '../../../chat/business logic layer/chat_controller.dart';
import '../../../chat/data_layer/model/room.dart';
import 'home.dart';

class SuperHome extends StatelessWidget {
  final List<Widget> screens = [
    HomeScreen(),
    FavoriteScreen(),
    ChatScreen(),
    AccountScreen(),
  ];
  final HomeController homeController = Get.find<HomeController>();
  final AuthController authController = Get.find<AuthController>();
  final ChatController chatController = Get.find<ChatController>();
  final FavoriteController favoriteController = Get.find<FavoriteController>();
  SuperHome({super.key});

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(microseconds: 100), () async {
      authController.isGuest.value =
          homeController.storage.getIsGuest() ?? true;
      if (!authController.isGuest.value) {
        chatController.init(handler: (message) {
          if (Get.currentRoute != RouteName.chatDetails &&
              chatController.chatUser.id != message.user.id) {
            Get.snackbar(
              'you have a message from ${message.user.name}',
              (message.type == MessageType.text)
                  ? message.content
                  : message.type.messageTypeString,
              onTap: (value) {
                Room room = chatController.getRoomById(message.roomId)!;

                chatController.setCurrentRoom(room);
                RoutingManager.to(RouteName.chatDetails, arguments: {
                  "room": room,
                });
              },
              backgroundColor: Colors.white,
              icon: const Icon(Icons.inbox),
              isDismissible: true,
              duration: const Duration(seconds: 5),
              dismissDirection: DismissDirection.horizontal,
            );
          }
        }, onSessionTerminated: (value) {
          Toast.showToast('this_session_is_terminated'.tr);
          RoutingManager.offAll(RouteName.login);
          // print('session terminated');
          authController.isGuest.update((val) {
            val = false;
          });
          LocalStorage().saveIsGuest(false);
          String? languangeCode = LocalStorage().getLanguage();
          LocalStorage().clearCache();
          if (languangeCode != null) {
            LocalStorage().saveLanguage(languangeCode);
          }
          homeController.storage.savefirstTimeOpened();
          homeController.selectIndex.value = 0;
          chatController.io.disconnect();
          chatController.clear();
          homeController.user.value = User.zero();
          favoriteController.getFavoriteState.update((val) {
            val!.value = [];
          });
          favoriteController.getFavoriteState.refresh();
        });
      }
      // FirebaseMessaging.instance
      //     .getInitialMessage()
      //     .then((remoteMessage) async {
      //   if (remoteMessage != null) {
      //     int cardId = int.parse(remoteMessage.data['id']);
      //     CardModel cardModel = await CardService().showCard(cardId: cardId);
      //     RoutingManager.to(RouteName.cardDetails, arguments: cardModel);
      //   }
      // });
    });

    return WillPopScope(
      onWillPop: () async {
        if (homeController.selectIndex.value != 0) {
          homeController.onPress(0);
          return false;
        } else {
          bool confirmissonResult = false;
          await Get.defaultDialog(
            title: '',
            content: Column(
              children: [
                Lottie.asset(
                  'assets/animations/Exit.json',
                  repeat: false,
                ),
                RegularTextWidget(
                  'are_you_sure_you_want_to_exit?'.tr,
                  textAlign: TextAlign.center,
                  fontSize: Responsive.isTablet() ? 22 : 18,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    TextButton(
                        onPressed: () {
                          confirmissonResult = true;
                          RoutingManager.back();
                        },
                        child: Text(
                          'yes'.tr,
                          style: TextStyle(
                            fontSize: Responsive.isTablet() ? 22 : 18,
                          ),
                        )),
                    TextButton(
                        onPressed: () {
                          confirmissonResult = false;
                          RoutingManager.back();
                        },
                        child: Text(
                          'no'.tr,
                          style: TextStyle(
                            fontSize: Responsive.isTablet() ? 22 : 18,
                          ),
                        )),
                  ],
                ),
              ],
            ).paddingSymmetric(horizontal: 4),
          );

          return confirmissonResult;
        }
      },
      child: Obx(() {
        return Scaffold(
          body: screens.elementAt(homeController.selectIndex.value),
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: homeController.selectIndex.value,
            onTap: homeController.onPress,
            selectedFontSize: 10,
            type: BottomNavigationBarType.fixed,
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                  icon: SvgPicture.asset(
                    colorFilter: ColorFilter.mode(
                        homeController.selectIndex.value == 0
                            ? AppColors.primeColor
                            : Colors.black,
                        BlendMode.srcIn),
                    homeController.selectIndex.value == 0
                        ? 'assets/icons/home.svg'
                        : 'assets/icons/home.svg',
                  ),
                  label: ''),
              BottomNavigationBarItem(
                  icon: SvgPicture.asset(
                    colorFilter: ColorFilter.mode(
                        homeController.selectIndex.value == 1
                            ? AppColors.primeColor
                            : Colors.black,
                        BlendMode.srcIn),
                    homeController.selectIndex.value == 1
                        ? 'assets/icons/love-svgrepo-com 1.svg'
                        : 'assets/icons/love-svgrepo-com 1.svg',
                  ),
                  label: ''),
              BottomNavigationBarItem(
                  icon: SvgPicture.asset(
                    colorFilter: ColorFilter.mode(
                        homeController.selectIndex.value == 2
                            ? AppColors.primeColor
                            : Colors.black,
                        BlendMode.srcIn),
                    homeController.selectIndex.value == 2
                        ? 'assets/icons/love-svgrepo-com 3.svg'
                        : 'assets/icons/love-svgrepo-com 3.svg',
                  ),
                  label: ''),
              BottomNavigationBarItem(
                icon: SvgPicture.asset(
                  colorFilter: ColorFilter.mode(
                      homeController.selectIndex.value == 3
                          ? AppColors.primeColor
                          : Colors.black,
                      BlendMode.srcIn),
                  homeController.selectIndex.value == 3
                      ? 'assets/icons/love-svgrepo-com 2.svg'
                      : 'assets/icons/love-svgrepo-com 2.svg',
                ),
                label: '',
              ),
            ],
          ),
        );
      }),
    );
  }
}
