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

import 'package:bot_toast/bot_toast.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_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/storage/hive_storage.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';
import 'package:wallpaperx/config/applovin.dart';
import 'package:wallpaperx/firebase/firebase_options.dart';
import 'package:wallpaperx/firebase/firebase_remote_config_manager.dart';
import 'package:wallpaperx/res/themes/app_themes.dart';
import 'package:wallpaperx/res/values/strings.dart';
import 'package:wallpaperx/routes/app_pages.dart';

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

  try {
    // 初始化Firebase
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    debugPrint("Firebase initialization OK");
  } catch (e) {
    debugPrint("Firebase initialization error: $e");
  }

  // 非异步错误
  FlutterError.onError = (errorDetails) {
    FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
  };

  // 异步错误
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: false);
    return true;
  };

  // 竖屏
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  // 初始化广告sdk
  await ApplovinUtil().initApplovin();

  UPCache.preInit();

  await FirebaseRemoteConfigManager().init();

  // 初始化Hive
  await initHive();

  // EasyLoading配置
  configLoading();

  // 沉浸式状态栏
  if (Platform.isAndroid) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.black,
      systemNavigationBarIconBrightness: Brightness.light,
      statusBarColor: Colors.transparent, // 状态栏背景色
      statusBarIconBrightness: Brightness.light, // 状态栏图标亮度
    ));
  }

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    final easyLoading = EasyLoading.init();
    return ScreenUtilInit(
      // 设计稿中设备的尺寸(单位随意,建议dp,但在使用过程中必须保持一致)
      designSize: const Size(375, 812),
      // 是否根据宽度/高度中的最小值适配文字
      minTextAdapt: true,
      // 支持分屏尺寸
      splitScreenMode: true,
      builder: (context, child) {
        final botToastBuilder = BotToastInit();
        return GetMaterialApp(
            title: appName,
            debugShowCheckedModeBanner: false,
            theme: lightTheme,
            themeMode: ThemeMode.dark,
            getPages: AppPages.routes,
            initialRoute: AppPages.splash,
            navigatorObservers: [BotToastNavigatorObserver()],
            builder: (context, widget) {
              widget = easyLoading(context, widget);
              child = botToastBuilder(context,widget);
              return MediaQuery(
                // 设置文字大小不随系统设置改变
                data: MediaQuery.of(context)
                    .copyWith(textScaler: TextScaler.noScaling),
                child: Scaffold(
                  resizeToAvoidBottomInset: false,
                  body: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                    },
                    child: child,
                  ),
                ),
              );
            },
            routingCallback: (routing) {
              LogPrint.d("路由变化 ${routing?.current}");
            });
      },
    );
  }
}
