import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
import 'package:laki_icu_app/blocs/auth/auth_bloc.dart';
import 'package:laki_icu_app/blocs/auth/auth_event.dart';
import 'package:laki_icu_app/blocs/auth/auth_state.dart';
import 'package:laki_icu_app/blocs/bluetooth_read/bluetooth_read_bloc.dart';
import 'package:laki_icu_app/routes/app_router.dart';
import 'package:laki_icu_app/repositories/auth_repository.dart';
import 'package:laki_icu_app/services/auth_service.dart';
import 'package:laki_icu_app/utils/http/dio_request.dart';
import 'package:laki_icu_app/utils/event_bus.dart';
import 'package:laki_icu_app/utils/storage/storage_service.dart';
import 'package:laki_icu_app/routes/app_router.gr.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:flutter_ume_plus/flutter_ume_plus.dart';
import 'package:flutter_ume_kit_console_plus/flutter_ume_kit_console_plus.dart';
// import 'package:flutter_ume_kit_device_plus/flutter_ume_kit_device_plus.dart';
import 'package:flutter_ume_kit_dio_plus/flutter_ume_kit_dio_plus.dart';
// import 'package:flutter_ume_kit_perf_plus/flutter_ume_kit_perf_plus.dart';
// import 'package:flutter_ume_kit_provider_plus/flutter_ume_kit_provider_plus.dart';
// import 'package:flutter_ume_kit_shared_preferences_plus/flutter_ume_kit_shared_preferences_plus.dart';
// import 'package:flutter_ume_kit_show_code_plus/flutter_ume_kit_show_code_plus.dart';
import 'package:flutter_ume_kit_ui_plus/flutter_ume_kit_ui_plus.dart';

import 'package:laki_icu_app/blocs/device_control/device_control_bloc.dart';
import 'package:marionette_flutter/marionette_flutter.dart';

Future<void> main(List<String> args) async {
  // 初始化 HydratedBloc 存储（用于持久化设备控制用户设置等）
  final storageDirectory = await getApplicationDocumentsDirectory();
  HydratedBloc.storage = await HydratedStorage.build(
    storageDirectory: storageDirectory,
  );

  // UME 调试工具（仅 Debug 模式启用）
  if (kDebugMode) {
    // MarionetteBinding 继承自 WidgetsFlutterBinding，必须最先且唯一初始化
    MarionetteBinding.ensureInitialized();

    PluginManager.instance
      ..register(WidgetInfoInspector())
      ..register(WidgetDetailInspector())
      ..register(Console());
    // ..register(DioInspector(dio: ApiClient.instance().dio));
    runApp(UMEWidget(enable: true, child: const MyApp()));
  } else {
    WidgetsFlutterBinding.ensureInitialized();
    runApp(const MyApp());
  }
  // runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
  late final StorageService _storageService;
  late final AuthService _authService;
  late final AppRouter _appRouter;
  late final AuthBloc _authBloc;
  BluetoothReadBloc? _bluetoothReadBloc;
  DeviceControlBloc? _deviceControlBloc;
  StreamSubscription? _tokenExpiredSubscription;
  bool _isInitializing = true;

  BluetoothReadBloc get _bluetoothReadBlocInstance =>
      _bluetoothReadBloc ??= BluetoothReadBloc(
        storageService: _storageService,
      );

  DeviceControlBloc get _deviceControlBlocInstance =>
      _deviceControlBloc ??= DeviceControlBloc();

  @override
  void initState() {
    super.initState();

    _storageService = StorageService();
    DioRequest.instance.init(_storageService);
    final authRepository = AuthRepository();
    _authService = AuthService(
      authRepository: authRepository,
      storageService: _storageService,
    );
    _authBloc = AuthBloc(
      authService: _authService,
      storageService: _storageService,
    );
    _appRouter = AppRouter();

    // 全局全屏：隐藏系统状态栏和底部导航栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);

    // 监听 Token 过期事件
    _tokenExpiredSubscription =
        eventBus.on<TokenExpiredEvent>().listen((event) {
      _authBloc.add(const AuthTokenExpiredEvent());
    });

    _checkTokenOnStartup();
  }

  Future<void> _checkTokenOnStartup() async {
    final hasToken = await _storageService.hasToken();
    if (hasToken) {
      final expired = await _authService.isTokenExpired();
      if (expired) {
        _authBloc.add(const AuthTokenExpiredEvent());
      } else {
        // Token 有效，尝试恢复用户信息
        _authBloc.add(const AuthFetchUserInfo());
      }
      _endInitializing();
    } else {
      // 无 Token，执行静默登录
      await _performSilentLogin();
    }
  }

  /// 静默登录核心逻辑：使用预设账号自动登录
  Future<void> _silentLogin() async {
    try {
      await _authService.login('13800000001', '111111');
      // 登录成功，获取用户信息
      _authBloc.add(const AuthFetchUserInfo());
    } catch (e) {
      // 静默登录失败，不做任何处理
    }
  }

  /// 启动时的静默登录，登录完成后结束初始化状态
  Future<void> _performSilentLogin() async {
    await _silentLogin();
    _endInitializing();
  }

  void _endInitializing() {
    if (mounted) {
      setState(() {
        _isInitializing = false;
      });
    }
  }

  Widget _buildSplash() {
    return Positioned.fill(
      child: ColoredBox(
        color: const Color(0xFFF5F7FA),
        child: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tokenExpiredSubscription?.cancel();
    _authBloc.close();
    _bluetoothReadBloc?.close();
    _deviceControlBloc?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(1920, 1199),
      builder: (context, child) {
        return MultiBlocProvider(
          providers: [
            BlocProvider<AuthBloc>.value(value: _authBloc),
            BlocProvider<BluetoothReadBloc>.value(
              value: _bluetoothReadBlocInstance,
            ),
            BlocProvider<DeviceControlBloc>.value(
              value: _deviceControlBlocInstance,
            ),
            // BlocProvider<CounterBloc>(create: (_) => CounterBloc()),
          ],
          child: MultiBlocListener(
            listeners: [
              // AuthBloc 监听器 - 处理登录/Token 过期/登出
              BlocListener<AuthBloc, AuthState>(
                listener: (context, state) {
                  if (state is AuthSuccess) {
                    _appRouter.replaceAll([const DefaultLayoutRoute()]);
                  }
                  if (state is AuthTokenExpired) {
                    _silentLogin();
                  }
                  if (state is AuthLoggedOut) {
                    _silentLogin();
                  }
                },
              ),
              // 未来在这里添加其他 Bloc 的监听器：
              // BlocListener<UserBloc, UserState>(listener: ...),
              // BlocListener<SettingsBloc, SettingsState>(listener: ...),
            ],
            child: Stack(
              children: [
                MaterialApp.router(
                  scaffoldMessengerKey: _scaffoldMessengerKey,
                  routerConfig: _appRouter.config(),
                  debugShowCheckedModeBanner: false,
                ),
                if (_isInitializing) _buildSplash(),
              ],
            ),
          ),
        );
      },
    );
  }
}
