import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/data/storage/hive_storage.dart';
import 'package:tone_snap/firebase/firebase_crashlytics_manager.dart';
import 'package:tone_snap/firebase/firebase_options.dart';
import 'package:tone_snap/global/app_config.dart';
import 'package:tone_snap/modules/sideb/controllers/main_controller.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';
import 'package:tone_snap/modules/sideb/music_bar/music_bar.dart';
import 'package:tone_snap/modules/sideb/music_bar/music_bar_controller.dart';
import 'package:tone_snap/res/themes/app_themes.dart';
import 'package:tone_snap/routes/app_pages.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/file_util.dart';
import 'package:tone_snap/utils/local_path_util.dart';
import 'package:tone_snap/utils/log_util.dart';

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

  // 初始化Firebase
  try {
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    await FirebaseCrashlyticsManager.setEnabled();
    FirebaseCrashlyticsManager.recordFlutterError();
    FirebaseCrashlyticsManager.recordError();
  } catch (e) {
    LogUtil.e("Firebase initialization error: $e");
  }

  // 初始化广告 SDK
  MobileAds.instance.initialize();

  // 初始化Hive
  await initHive();

  runApp(const MyApp());

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

  // 设置安卓状态栏背景色透明、底部导航栏颜色和导航栏图标亮度
  if (Platform.isAndroid) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.black,
      systemNavigationBarIconBrightness: Brightness.light,
    ));
  }

  // 删除缓存文件
  FileUtil.deleteAllFilesInDirectory(await LocalPathUtil.getRecordingsDir());
  FileUtil.deleteAllFilesInDirectory(await LocalPathUtil.getAssetsDir());
}

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

  @override
  Widget build(BuildContext context) {
    final easyLoading = EasyLoading.init();
    List<NavigatorObserver> navigatorObservers = const <NavigatorObserver>[];
    navigatorObservers = [
      GetObserver((_) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (Get.currentRoute == AppRoutes.playPage) {
            MusicBar().hide();
          } else {
            if (Get.isRegistered<MusicPlayerController>()) {
              if (MusicPlayerController.to.getMusicModel()?.value.videoId != null) {
                if (Get.isBottomSheetOpen != null && Get.isBottomSheetOpen!) {
                  MusicBar().hide();
                } else {
                  MusicBar().show();
                }
              }
            }
          }
          if (Get.isRegistered<MusicBarController>()) {
            if (Get.currentRoute == AppRoutes.initialB) {
              MusicBarController.to.riseUp();
            } else {
              MusicBarController.to.toBottom();
            }
          }
        });
      }),
    ];
    return ScreenUtilInit(
      // 以设计稿的尺寸为基准进行适配
      designSize: const Size(375, 812),
      minTextAdapt: true,
      builder: (context, child) {
        return KeyboardDismissOnTap(
          dismissOnCapturedTaps: true,
          child: GetBuilder(
            id: 'changeTheme',
            init: MainController(),
            builder: (logic) {
              return GetMaterialApp(
                title: AppConfig.appName,
                debugShowCheckedModeBanner: false,
                theme: logic.isSideBTheme.value ? sideBTheme : sideATheme,
                darkTheme: logic.isSideBTheme.value ? sideBTheme : sideATheme,
                themeMode: ThemeMode.dark,
                initialRoute: AppRoutes.launch,
                getPages: AppPages.routes,
                navigatorObservers: navigatorObservers,
                builder: (context, widget) {
                  BaseEasyLoading.configLoading();
                  widget = easyLoading(context, widget);
                  // 设置文字大小不随系统设置改变
                  return MediaQuery.withNoTextScaling(child: widget);
                },
              );
            },
          ),
        );
      },
    );
  }
}
