import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:page_transition/page_transition.dart';
import 'package:provider/provider.dart';
import 'package:quick_notify_2/quick_notify.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.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/history_forum.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/message_list.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/dio_logging_interceptors.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:upgrader/upgrader.dart';
import 'package:http/http.dart' as http;
import 'package:telnow_mobile_new/src/api/jwt_token.dart';

import 'app_router.dart';

// final SharedPreferencesManager _sharedPreferencesManager = locator<SharedPreferencesManager>();
var isDebug = true;

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  }
}

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();

  try{
    if (kIsWeb){
      await Firebase.initializeApp(
          options: FirebaseOptions(
              apiKey: "AIzaSyDlJQaEV9aPnPFeFA7QeiVijoGZXqemCRw",
              authDomain: "telmessenger-d3935.firebaseapp.com",
              databaseURL: "https://telmessenger-d3935.firebaseio.com",
              projectId: "telmessenger-d3935",
              storageBucket: "telmessenger-d3935.appspot.com",
              messagingSenderId: "647562261340",
              appId: "1:647562261340:web:01b97a27460e4bfd5b0799",
              measurementId: "G-BFCBWCK70H"
          )
      );
    }
    else{
      await Firebase.initializeApp();
      await U.flutterLocalNotificationsPlugin.cancelAll();
      await U.flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(U.channel);
    }

    await setupLocator();
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    HttpOverrides.global = new MyHttpOverrides();
    // WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
    // FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
    runApp(
        EasyLocalization(
            path: 'assets/lang',
            supportedLocales: [
              Locale('en'),
              Locale('id'),
              Locale('ja'),
              Locale('zh'),
              Locale('ko'),
              Locale('ar')
            ],
            startLocale: Locale('id'),
            saveLocale: true,
            child: MyApp()
        )
    );
  } catch (error, stacktrace) {
    print('$error & $stacktrace');
  }
}

class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices {
    return {
      PointerDeviceKind.touch,
      PointerDeviceKind.mouse,
    };
  }
}

class MyApp extends StatelessWidget {
  MyApp({super.key});
  final _appRouter = AppRouter();

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserModule()),
        ChangeNotifierProvider(create: (_) => ServiceModule()),
        ChangeNotifierProvider(create: (_) => HistoryModule()),
        ChangeNotifierProvider(create: (_) => RequestModule()),
        ChangeNotifierProvider(create: (_) => CreateSerModule()),
        ChangeNotifierProvider(create: (_) => MessageModule()),
      ],
      child: MaterialApp.router(
        scrollBehavior: MyCustomScrollBehavior(),
        debugShowCheckedModeBanner: false,
        localizationsDelegates: context.localizationDelegates,
        supportedLocales: context.supportedLocales,
        locale: context.locale,
        key: NavigationService.navigatorKey,
        theme: ThemeData(useMaterial3: false, fontFamily: 'SF Compact Display', appBarTheme: AppBarTheme(
          systemOverlayStyle: SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark,
              statusBarBrightness: Brightness.dark
          ),
        ), colorScheme: ColorScheme.fromSeed(seedColor: Color(0xff078C84))),
        routerConfig: _appRouter.config(),
      ),
    );
  }
}


class NavigationService {
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
}

@RoutePage()
class HomeGuardPage extends StatefulWidget {
  const HomeGuardPage({Key? key}) : super(key: key);

  @override
  State<HomeGuardPage> createState() => _HomeGuardPageState();
}

class _HomeGuardPageState extends State<HomeGuardPage> {
  late DateTime currentBackPressTime;
  JwtToken token = JwtToken();
  @override
  Widget build(BuildContext context) {
    eventBus.on().listen((event) {
      print("eventBus => ${event.toString()}");
      if(event.toString() == 'logout') {
        // token.logout();
        context.navigateToPath('/end-session');
        // return;
      }
    });
    // TODO: implement build
    return Scaffold(
      body: !kIsWeb ? UpgradeAlert(child: AutoRouter()):AutoRouter(),
    );
  }

  Future<bool> onWillPop() {
    DateTime now = DateTime.now();
    if (now.difference(currentBackPressTime) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      Fluttertoast.showToast(msg: 'pressAgain'.tr());
      return Future.value(false);
    }
    return Future.value(true);
  }
}

class NotificationClass {
  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();

  initFirebaseMessaging(BuildContext context) {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      var mid = message.data['mid'];
      var token = await U.getFcmToken();
      // print('tokennya');
      // print(token);
      if (token != null) {
        _apiAuthProvider.postDataNoAuth('/api/notifications/received/$token/$mid').then((value) =>
            print('sukses kirim confirm')
        );
      }

      if(kIsWeb){
        QuickNotify.notify(
          title: message.data['subject'],
          content: context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'],
        );
      }
      else{
        const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('notification_icon');
        final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid);
        // U.flutterLocalNotificationsPlugin.initialize(initializationSettings,);
        U.flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
          if (notificationResponse.payload != null) {
            var list = jsonDecode(notificationResponse.payload!);
            goNotification(list, context);
          }
        });

        var androidPlatformChannelSpecifics = AndroidNotificationDetails(
            'notification_channel2', // id
            'Normal Notification', // title
            channelDescription: 'This channel is used for normal notifications.', // description
            importance: Importance.max,
            priority: Priority.high,
            color: Color(0xff0D497F),
            styleInformation: BigTextStyleInformation(''),
            playSound: true,
            enableVibration: true,
            // sound: RawResourceAndroidNotificationSound('notification_alarm'),
            largeIcon: DrawableResourceAndroidBitmap('banner_icon_blue'),
            setAsGroupSummary: true,
            groupKey: message.data['subject']
        );
        var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
        U.flutterLocalNotificationsPlugin.show(0, message.data['subject'],
            context.locale.toString() == 'id' ? message.data['description'] : message.data['descriptionEn'], platformChannelSpecifics,
            payload: jsonEncode(message.data));
      }
    });

    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null && !U.hidePayload) {
        // print(message.data);
        goNotification(message.data, context);
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      U.setHidePayload(false);
      goNotification(message.data, context);
    });
  }

  getActiveNotif() async {
    List<ActiveNotification>? activeNotif = await U.flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.getActiveNotifications();
    return activeNotif;
  }

  startNotification(BuildContext context) async {
    var token = await U.getFcmToken();
    if (token != null) {
      Map data = {'token': token, 'language': context.locale.toString().toUpperCase()};
      var res = _apiAuthProvider.postData('/api/fcmTokens/register', null, data, context);
      return res;
    }
  }

  stopNotification(BuildContext context) async {
    var token = await U.getFcmToken();
    if (token != null) {
      var res = _apiAuthProvider.postData('/api/fcmTokens/remove/$token', null, null, context);
      return res;
    }
  }

  goNotification(list, BuildContext context) {
    if (list['type'] == 'MESSAGE') {
      Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobMessageListPage(null)));
    }
    else if (list['type'] == 'FORUM') {
      // print(list['requestHistory']);
      Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobHistoryForumPage(data: jsonDecode(list['requestHistory']))));
    }
    else{
      var pid = U.getPidFromUrl(context.router.currentUrl);
      context.router.removeLast();
      context.navigateToPath("/app/$pid/menu/history");
    }
    // if (list['type'] == 'FORUM') {
    //   Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: Forum(list['info'], list['currentStatus'] == 'DIMULAI' || list['currentStatus'] == 'DISELESAIKAN' ? true : false)));
    // } else {
    //   Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: DetailMisi(list['info'])));
    // }
  }
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.reload();

  // print('background : ${message.data}');
  String accCode = prefs.getString(SharedPreferencesManager.keyAccessCode)!;
  var decAccCode = U.decodeBase64Url(accCode);
  var mid = message.data['mid'];
  FirebaseMessaging.instance.getToken().then((token) async {
    if (token != null) {
      http.post(Uri.https(U.decodeBase64Url(prefs.getString(SharedPreferencesManager.keyBaseUrl)!).split('//')[1], '$decAccCode/api/notifications/received/$token/$mid')).then((value) {
        print("kirim confirm");
        prefs.setString(SharedPreferencesManager.lastMid, mid);
      });
    }
  });
}