import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/blocs/auth/auth_bloc.dart';
import 'package:smart_hotel_app/blocs/auth/auth_event.dart';
import 'package:smart_hotel_app/blocs/auth/auth_state.dart'; 
import 'package:smart_hotel_app/routes/app_router.dart';
import 'package:smart_hotel_app/repositories/auth_repository.dart';
import 'package:smart_hotel_app/services/auth_service.dart';
import 'package:smart_hotel_app/utils/http/dio_request.dart';
import 'package:smart_hotel_app/utils/event_bus.dart';
import 'package:smart_hotel_app/utils/storage/storage_service.dart';
import 'package:smart_hotel_app/utils/toast_utils.dart';
import 'package:smart_hotel_app/routes/app_router.gr.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; 

void main(List<String> args) {
  WidgetsFlutterBinding.ensureInitialized();
  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;
  StreamSubscription? _tokenExpiredSubscription;

  @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();

    // 监听 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());
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(750, 1334),
      builder: (context, child) {
        return MultiBlocProvider(
          providers: [
            BlocProvider<AuthBloc>.value(value: _authBloc),
            // 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) {
                    showToast('登录已过期，请重新登录');
                    _appRouter.replaceAll([LoginRoute()]);
                  }
                  if (state is AuthLoggedOut) {
                    _appRouter.replaceAll([LoginRoute()]);
                  }
                },
              ),
              // 未来在这里添加其他 Bloc 的监听器：
              // BlocListener<UserBloc, UserState>(listener: ...),
              // BlocListener<SettingsBloc, SettingsState>(listener: ...),
            ],
            child: MaterialApp.router(
              scaffoldMessengerKey: _scaffoldMessengerKey,
              routerConfig: _appRouter.config(),
              debugShowCheckedModeBanner: false,
            ),
          ),
        );
      },
    );
  }
}
