import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:double_back_to_exit/double_back_to_exit.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:lazy_load_indexed_stack/lazy_load_indexed_stack.dart';
import 'package:quick_notify_2/quick_notify.dart';
import 'package:simple_connection_checker/simple_connection_checker.dart';
import 'package:telnow_mobile_new/main.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/menu_account.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/menu_history.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/menu_home.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/ui_service.dart';

class MobAppPage extends StatefulWidget {
  final Widget child;
  const MobAppPage(this.child, {super.key});

  @override
  State<MobAppPage> createState() => _MobAppPageState();
}

class _MobAppPageState extends State<MobAppPage>with TickerProviderStateMixin {
  final NotificationClass notification = NotificationClass();
  late AnimationController _animationController;
  StreamSubscription? subscription;
  bool isConnected = true;
  bool begin = false;

  @override
  void initState() {
    if(!kIsWeb){
      _animationController = new AnimationController(duration: Duration(seconds: 2), vsync: this);
      _animationController.repeat(reverse: true);
      checkConnection();
    }
    else{
      U.getServerVersion();
      // getOtherList();
      begin = true;
    }

    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    if(!kIsWeb) {
      subscription?.cancel();
      _animationController.dispose();
    }

    // TODO: implement dispose
    super.dispose();
  }

  checkConnection() async{
    await U.getServerVersion();
    final ctx = UIService.context;
    var langCode = ctx!.locale.toString();

    void initFirebase(){
      notification.initFirebaseMessaging(context);
    }

    void checkPendingRequest(){
      U.checkPendingRequest(context);
      if(ModalRoute.of(context)?.isCurrent != true) navigateBack(context);
    }

    SimpleConnectionChecker simpleConnectionChecker = SimpleConnectionChecker();
    subscription = simpleConnectionChecker.onConnectionChange.listen((connected) {
      U.setInternetStatus(connected);
      setState(() => begin = true);
      if(connected){
        setState(() => isConnected = true);
        initFirebase();
        var valLang = U.retValidLang();
        int? code;
        if(valLang.indexOf(langCode) > 1){
          code = valLang.indexOf(langCode) - 1;
        }
        notification.startNotification(code: code);
        checkPendingRequest();
      } else {
        Future.delayed(Duration(seconds: 4), (){
          if(!U.getInternetStatus()){
            UIService.handlingError(ErrorType.noInternet);
            setState(() => isConnected = false);
          }
        });
      }
    });
  }

  getOtherList(){
    U.getOtherLabelList(context);
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          begin ? widget.child : Container(),
          isConnected?Container():IgnorePointer(
            child: FadeTransition(opacity: _animationController, child: Container(
              width: double.infinity, color: Colors.red,
              margin: EdgeInsets.only(bottom: 56),
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
              child: Text('noInternetTitle'.tr(), style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
            )),
          )
        ],
      ),
    );
  }
}

//---------------------------------------------------------------------------------------------------------------

class MobMenuTemplate extends StatefulWidget {
  // final Widget child;
  const MobMenuTemplate({super.key});

  @override
  State<MobMenuTemplate> createState() => _MobMenuTemplateState();
}

class _MobMenuTemplateState extends State<MobMenuTemplate> {
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  bool historyMark = false;

  getUser() async {
    if(kIsWeb){
      if(!await QuickNotify.hasPermission()){
        await QuickNotify.requestPermission();
      }
    }

    if(sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyHistoryMark)!){
      setState(() => historyMark = sharedPreferencesManager.getBool(SharedPreferencesManager.keyHistoryMark)!);
    }
    FirebaseMessaging.onMessage.listen((event) {
      if(event.data['type'] != 'MESSAGE'){
        if(!context.router.currentUrl.endsWith("history") && mounted){
          setState(() => historyMark = true);
          sharedPreferencesManager.putBool(SharedPreferencesManager.keyHistoryMark, true);
        }
      }
    });
  }

  indexedStack(index){
    return LazyLoadIndexedStack(
      index: index,
      children: [
        MobHomePage(),
        MobHistoryPage(),
        MobAccountPage()
      ],
    );
  }

  @override
  void initState() {
    getUser();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var index = 0;
    if(context.router.currentUrl.endsWith("history")){
      index = 1;
      historyMark = false;
      sharedPreferencesManager.putBool(SharedPreferencesManager.keyHistoryMark, false);
    }else if(context.router.currentUrl.endsWith("account")){
      index = 2;
    }

    return Scaffold(
      backgroundColor: backgroundColor,
      body: !kIsWeb ? DoubleBackToExit(
        snackBarMessage: 'pressAgain'.tr(),
        child: indexedStack(index)
      ) : indexedStack(index),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        selectedItemColor: textColor,
        unselectedItemColor: textColor,
        type: BottomNavigationBarType.fixed,
        onTap: (value) {
          var pid = U.getPidFromUrl(context.router.currentUrl);
          if(value!=index) {
            switch (value) {
              case 0:
                context.router.removeLast();
                  context.navigateToPath("/app/$pid/menu/home");
                break;
              case 1:
                context.router.removeLast();
                  context.navigateToPath("/app/$pid/menu/history");
                break;
              default:
                context.router.removeLast();
                  context.navigateToPath("/app/$pid/menu/account");
                break;
            }
          }
        },
        currentIndex: index,
        showUnselectedLabels: true,
        selectedFontSize: 12,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: U.iconsax(index == 0 ? 'bold/home' : 'home-1', color: index==0 ? primaryColor : Color(0xff292D32).withValues(alpha: 0.5)), label: 'menuHome'.tr()),
          BottomNavigationBarItem(icon: Center(
            child: Stack(
              alignment: Alignment.topRight,
              children: [
                U.iconsax(index == 1 ? 'bold/archive-2' : 'archive-2', color: index==1 ? primaryColor : Color(0xff292D32).withValues(alpha: 0.5)),
                Container(
                  width: historyMark?11:0, height: historyMark?11:0,
                  decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.all(Radius.circular(50))),
                )
              ],
            ),
          ), label: 'menuHistory'.tr()),
          BottomNavigationBarItem(icon: U.iconsax(index == 2 ? 'bold/personalcard' : 'personalcard', color: index==2 ? primaryColor : Color(0xff292D32).withValues(alpha: 0.5)), label: 'menuAccount'.tr()),
        ],
      ),
    );
  }
}
