import 'package:cpt_main/router/component/main_service_provider.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:cs_resources/theme/theme_notifier.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:initializer/app_initializer.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/app_config/app_config_service.dart';
import 'package:plugin_basic/provider/global_provider_container.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:cpt_profile/router/component/profile_service_provider.dart';
import 'package:plugin_basic/obs/my_navigator_observer.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/custom_toast_widget.dart';
import 'package:widgets/dialog/custom_error_widget.dart';
import 'package:widgets/dialog/custom_failure_widget.dart';
import 'package:widgets/dialog/custom_success_widget.dart';
import 'package:widgets/dialog/custom_loading_widget.dart';
import 'package:widgets/widget_export.dart';
import 'package:cs_resources/theme/theme_config.dart';
import 'firebase_options.dart';
import 'router/page/app_page_router.dart';
import 'router/component/app_service_provider.dart';
import 'package:cpt_auth/router/component/auth_component_service.dart';
import 'package:cpt_community/router/component/community_component_service.dart';
import 'package:cpt_facility/router/component/facility_component_service.dart';
import 'package:cpt_form/router/component/form_component_service.dart';
import 'package:cpt_notice_board/router/component/notice_board_component_service.dart';
import 'package:cpt_payment/router/component/payment_component_service.dart';
import 'package:cpt_property/router/component/property_component_service.dart';
import 'package:cpt_rewards/router/component/rewards_component_service.dart';
import 'package:cpt_services/router/component/services_component_service.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  //交给初始化构造器去统一初始化
  await AppInitializer.initializeRunalone();

  //初始化FCM
  Firebase.initializeApp(name: '24IFM', options: MyFirebaseOptions.currentPlatform);

  //组件路由的注入
  ComponentServiceManager()
    ..addServiceProvider(mainServiceProvider)
    ..addServiceProvider(authServiceProvider)
    ..addServiceProvider(appServiceProvider)
    ..addServiceProvider(communityServiceProvider)
    ..addServiceProvider(facilityServiceProvider)
    ..addServiceProvider(formServiceProvider)
    ..addServiceProvider(noticeBoardServiceProvider)
    ..addServiceProvider(paymentServiceProvider)
    ..addServiceProvider(propertyServiceProvider)
    ..addServiceProvider(rewardsServiceProvider)
    ..addServiceProvider(servicesServiceProvider)
    ..addServiceProvider(profileServiceProvider);

  runApp(UncontrolledProviderScope(
    container: globalContainer,
    child: MyApp(),
  ));
}

class MyApp extends HookConsumerWidget {
  MyApp({Key? key}) : super(key: key) {
    /// 全局设置 EasyRefresh 的样式
    EasyRefresh.defaultHeaderBuilder = () => const ClassicHeader(
          dragText: 'Pull to refresh',
          armedText: 'Release ready',
          readyText: 'Refreshing...',
          processingText: 'Refreshing...',
          processedText: 'Succeeded',
          noMoreText: 'No more',
          failedText: 'Failed',
          messageText: 'Last updated at %T',
          backgroundColor: Colors.transparent,
        );
    EasyRefresh.defaultFooterBuilder = () => const ClassicFooter(
          dragText: 'Pull to load',
          armedText: 'Release ready',
          readyText: 'Loading...',
          processingText: 'Loading...',
          processedText: 'Succeeded',
          noMoreText: 'No more',
          failedText: 'Failed',
          showMessage: false,
          triggerOffset: 50,
          iconDimension: 22,
          backgroundColor: Colors.transparent,
        );

    /// SmartDialog 配置
    SmartDialog.config
      ..custom = SmartConfigCustom(
        maskColor: Colors.black.withOpacity(0.35),
        useAnimation: true,
      )
      ..attach = SmartConfigAttach(
        animationType: SmartAnimationType.scale,
        usePenetrate: false,
      )
      ..loading = SmartConfigLoading(
        // SmartConfigCustomSmartConfigCustomSmartConfigCustom
        clickMaskDismiss: true,
      )
      ..toast = SmartConfigToast(
        intervalTime: const Duration(milliseconds: 100),
        displayTime: const Duration(milliseconds: 2000),
      );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeMode = ref.watch(themeProvider);

    //根据主题配置对应的状态栏
    int? darkModel = SPUtil.getInt(AppConstant.storageDarkModel, defValue: 0);
    late SystemUiOverlayStyle systemUiOverlayStyle;

    //根据SP存入的暗色模式，指定全局页面的状态栏，导航栏等设置
    switch (darkModel) {
      case 1:
        Log.d("main.dart - 指定亮色模式");
        systemUiOverlayStyle = ThemeConfig.systemUiOverlayStyleLightThemeBlack;
        break;
      case 2:
        Log.d("main.dart - 指定暗色模式");
        systemUiOverlayStyle = ThemeConfig.systemUiOverlayStyleDarkTheme;
        break;
      default:
        systemUiOverlayStyle = ThemeConfig.getSystemUiOverlayStyleByTheme(context);
        break;
    }

    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

    useEffect(() {
      // 组件挂载时执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        //控件加载完成时执行
        AppConfigService.getInstance().initSize(context);
      });
      return () {
        // 组件卸载时执行
        globalContainer.dispose();
      };
    }, []);

    return KeyboardVisibilityBuilder(builder: (context, isKeyboardVisible) {
      return KeyboardDismissOnTap(
        dismissOnCapturedTaps: false,
        child: MaterialApp.router(
          title: 'PropertyManagementSystem',
          debugShowCheckedModeBanner: true,

          //主题配置
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: AppColorsTheme.colorPrimary),
            useMaterial3: false,
          ).copyWith(extensions: [
            AppColorsTheme.light(),
          ]),
          darkTheme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: AppColorsTheme.colorPrimary, brightness: Brightness.dark),
            useMaterial3: false,
          ).copyWith(extensions: [
            AppColorsTheme.dark(),
          ]),
          themeMode: themeMode == ThemeMode.system ? ThemeMode.system : themeMode,

          //国际化配置
          localizationsDelegates: const [
            S.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          //国际化英语为首选项
          supportedLocales: [const Locale('en', ''), ...S.delegate.supportedLocales],
          localeResolutionCallback: (locale, supportLocales) {
            // 中文 简繁体处理
            if (locale?.languageCode == 'zh') {
              if (locale?.scriptCode == 'Hant') {
                return const Locale('zh', 'HK'); //繁体
              } else {
                return const Locale('zh', 'CN'); //简体
              }
            }
            return null;
          },
          //AutoRouter的配置
          routerConfig: appRouter.config(
            navigatorObservers: () => [
              MyNavigatorObserver(),
            ],
          ),
          //SmartDialog初始化默认Loading与Toast
          builder: FlutterSmartDialog.init(
            toastBuilder: (String msg) {
              return CustomToastWidget(msg: msg);
            },
            loadingBuilder: (String msg) {
              return CustomLoadingWidget(msg: msg == 'loading...' ? 'Loading...' : msg);
            },
            notifyStyle: FlutterSmartNotifyStyle(
              successBuilder: (String msg) => CustomSuccessWidget(msg: msg),
              failureBuilder: (String msg) => CustomFailureWidget(msg: msg),
              errorBuilder: (String msg) => CustomErrorWidget(msg: msg),
              alertBuilder: (String msg) => CustomErrorWidget(msg: msg),
              warningBuilder: (String msg) => CustomErrorWidget(msg: msg),
            ),
          ),
        ),
      );
    });
  }
}
