import 'dart:async';
import 'dart:developer';
import 'dart:io';

import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jailbreak_root_detection/jailbreak_root_detection.dart';
import 'package:mnemo_cards/di/locator.dart';
import 'package:mnemo_cards/domain/router/app_router.dart';
import 'package:mnemo_cards/managers/repository/firebase_config_repository.dart';
import 'package:mnemo_cards/features/packs/pack_manager.dart';
import 'package:mnemo_cards/theme/themes.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import 'package:no_screenshot/no_screenshot.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:yandex_mobileads/mobile_ads.dart';

import 'di/injector.dart';
import 'domain/router/app_router.gr.dart';
import 'firebase_options.dart';
import 'flags.dart';
import 'managers/repository/repository.dart';

final scaffoldKey = GlobalKey<ScaffoldState>();
final scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
late final SharedPreferences globalSharedPreferences;

final appRouter = AppRouter(ADMIN_BUILD);

AndroidDeviceInfo? androidDeviceInfo;

Future<bool> _screenOff() async =>
    ADMIN_BUILD || await NoScreenshot.instance.screenshotOff();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final stopwatch = Stopwatch()..start();
  print('ensureInitialized ${stopwatch.elapsedMilliseconds}');
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  androidDeviceInfo = await DeviceInfoPlugin().androidInfo;
  print('deviceInfo ${stopwatch.elapsedMilliseconds}');
  final isNotTrust = await JailbreakRootDetection.instance.isNotTrust;
  print('No trunst ${stopwatch.elapsedMilliseconds}');
  if (isNotTrust && !ADMIN_BUILD) {
    print('Not trusted');
    return;
  }
  final off = await _screenOff();
  print('screenshot off ${stopwatch.elapsedMilliseconds}');
  if (!off) {
    print('Cant disable screenhsot');
    return;
  }

  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
  };

  try {
    globalSharedPreferences = await SharedPreferences.getInstance();
    print('global sp ${stopwatch.elapsedMilliseconds}');
    await setInjections();
    print('injections ${stopwatch.elapsedMilliseconds}');
    unawaited(initFirebase());
    print('initing... ${stopwatch.elapsedMilliseconds}');
    await locator.packCacheManager.init();
    await locator.previewPackHolder.init();
    await locator.previewPackPoller.init();
    await locator.packManager.init();
    await locator.userManager.init();
    await locator.favoriteCardsController.init();
    await locator.previewPackPoller.init();
    await locator.packUpdater.init();
    print('initing complete ${stopwatch.elapsedMilliseconds}');
    await MobileAds.initialize();
    print('mobile ads ${stopwatch.elapsedMilliseconds}');
    print('runApp ${stopwatch.elapsedMilliseconds}');
    runApp(const MyApp());
  } on Object catch (e, s) {
    log(e.toString(), stackTrace: s);
    exit(0);
  }
}

Future<void> initFirebase() async {
  try {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    await FirebaseRepository.update();
  } on Object catch (e, s) {
    log('Firebase not inited', error: e, stackTrace: s);
  }
}

class MyApp extends StatelessWidget with WidgetsBindingObserver {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addObserver(this);
    return ScreenUtilInit(
      designSize: const Size(370, 800),
      minTextAdapt: true,
      splitScreenMode: true,
      child: MaterialApp.router(
        theme: lightTheme,
        routerConfig: appRouter.config(),
        scaffoldMessengerKey: scaffoldMessengerKey,
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _screenOff();
        break;
      case AppLifecycleState.inactive:
        _screenOff();
        break;
      case AppLifecycleState.paused:
        _screenOff();
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }
}

@RoutePage()
class MainTabsPage extends StatefulWidget {
  const MainTabsPage({super.key});

  @override
  State<MainTabsPage> createState() => _MainTabsPageState();
}

class _MainTabsPageState extends State<MainTabsPage> {
  late List<CardPackDto> cardPacks;
  late List<GameCardDto> cards;
  CardPackDto? pack;

  late Repository repository;
  late PackManager packManager;

  _Tabs _currentTab = _Tabs.home;

  @override
  void initState() {
    super.initState();
    repository = locator.repository;
    packManager = locator.packManager;
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).textTheme;
    return AutoTabsRouter.tabBar(
      key: scaffoldKey,
      homeIndex: 0,
      routes: [
        PageRouteInfo(HomePage.name),
        // PageRouteInfo(ExplorePage.name),
        // PageRouteInfo(ProfilePage.name),
      ],
      builder: (_, child, tabsController) => Scaffold(
        body: child,
        // bottomNavigationBar: Container(
        //   child: DotNavigationBar(
        //     currentIndex: tabsController.index,
        //     dotIndicatorColor: Colors.white,
        //     unselectedItemColor: Colors.grey[300],
        //     marginR: EdgeInsets.symmetric(horizontal: 32),
        //     itemPadding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),
        //     duration: Duration(milliseconds: 300),
        //     paddingR: EdgeInsets.zero,
        //     borderRadius: 32,
        //     enableFloatingNavBar: true,
        //     enablePaddingAnimation: false,
        //     splashBorderRadius: 32,
        //     boxShadow: [
        //       BoxShadow(
        //         color: Colors.black26,
        //         blurRadius: 8.0,
        //       )
        //     ],
        //     onTap: (i) {
        //       tabsController.index = i;
        //     },
        //     items: [
        //       /// Home
        //       DotNavigationBarItem(
        //         icon: Icon(
        //           Icons.home,
        //           size: 32,
        //         ),
        //         selectedColor: Colors.redAccent,
        //       ),
        //
        //       /// Search
        //       DotNavigationBarItem(
        //         icon: Icon(
        //           Icons.search,
        //           size: 32,
        //         ),
        //         selectedColor: Colors.redAccent,
        //       ),
        //
        //       /// Profile
        //       DotNavigationBarItem(
        //         icon: Icon(
        //           Icons.person,
        //           size: 32,
        //         ),
        //         selectedColor: Colors.redAccent,
        //       ),
        //     ],
        //   ),
        // ),
      ),
    );
  }
}

enum _Tabs { home, packs, profile }
