import 'package:flutter/material.dart';
import 'package:qhd_prevention/pages/badge_manager.dart';
import 'package:qhd_prevention/pages/http/HttpManager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './pages/login_page.dart';
import './pages/main_tab.dart';
import 'package:intl/date_symbol_data_local.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';

// 全局导航键
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// 全局消息控制器
class GlobalMessage {
  static void showError(String message) {
    final context = navigatorKey.currentContext;
    if (context != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }
}

void main() async {
  // 确保Flutter引擎初始化完成
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 EasyLoading
  // 配置 EasyLoading 全局实例
  EasyLoading.instance
    ..displayDuration = const Duration(seconds: 20)
    ..indicatorType = EasyLoadingIndicatorType.ring // 使用环形指示器
    ..loadingStyle = EasyLoadingStyle.custom // 必须使用自定义样式
    ..indicatorSize = 36.0 // 接近系统默认大小
    ..radius = 0 // 无圆角
    ..progressColor = Colors.blue // 进度条颜色为系统蓝色
    ..backgroundColor = Colors.grey.shade300
    ..indicatorColor = Colors.blue // 指示器颜色为系统蓝色
    ..textColor = Colors.black // 隐藏文字
    ..userInteractions = false // 允许用户交互（系统指示器不阻止交互）
    ..dismissOnTap = false;

  await initializeDateFormatting('zh_CN', null);
  // 获取共享首选项实例
  final prefs = await SharedPreferences.getInstance();

  // 获取登录状态
  final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;

  // 初始化HTTP管理器
  HttpManager.onUnauthorized = () async {
    // 清除登录状态
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isLoggedIn', false);
    await prefs.remove('token'); // 如果有token的话

    // 导航到登录页
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      '/login',
          (route) => false,
    );

    // 等一帧让页面构建完成
    Future.delayed(const Duration(milliseconds: 100), () {
      GlobalMessage.showError('会话已过期，请重新登录');
    });
  };

  runApp(MyApp(isLoggedIn: isLoggedIn));
}

class MyApp extends StatelessWidget {
  final bool isLoggedIn;

  MyApp({super.key, required this.isLoggedIn});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '',
      navigatorKey: navigatorKey, // 设置全局导航键
      builder: (context, child) {
        // 修复：正确集成 EasyLoading 和 GestureDetector
        return EasyLoading.init(
          builder: (context, widget) {
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                FocusScope.of(context).unfocus();
              },
              child: widget,
            );
          },
        )(context, child);
      },
      theme: ThemeData(
        dividerTheme: const DividerThemeData(
          color: Colors.black12,
          thickness: .5,      // 线高
          indent: 0,         // 左缩进
          endIndent: 0,      // 右缩进
        ),
        primarySwatch: Colors.blue,
        // 统一设置页面背景颜色
        scaffoldBackgroundColor: const Color(0xFFF1F1F1), // 浅灰色背景
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        inputDecorationTheme: const InputDecorationTheme(
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(horizontal: 8),
        ),
        snackBarTheme: const SnackBarThemeData(
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8)),
          ),
        ),
        progressIndicatorTheme: const ProgressIndicatorThemeData(
          color: Colors.blue, // 统一颜色
        ),
      ),
      // 根据登录状态决定初始页面
      home: isLoggedIn ? const MainPage() : const LoginPage(),
      debugShowCheckedModeBanner: false,
      routes: {
        '/login': (_) => const LoginPage(),
        // ... 其他路由
      },
    );
  }
}