import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'core/di/injection.dart';
import 'core/router/app_router.dart';
import 'core/constants/app_colors.dart';
import 'core/network/api_client.dart';
import 'core/router/routes.dart';
import 'core/updater/updater.dart';
import 'presentation/providers/user_providers.dart';
import 'presentation/providers/settings_providers.dart';

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

  // 初始化 Hive
  await Hive.initFlutter();

  // 初始化依赖注入
  await configureDependencies();

  // 初始化更新服务
  UpdateService.instance.initialize();

  runApp(const ProviderScope(child: MiningApp()));
}

class MiningApp extends ConsumerStatefulWidget {
  const MiningApp({super.key});

  @override
  ConsumerState<MiningApp> createState() => _MiningAppState();
}

class _MiningAppState extends ConsumerState<MiningApp> {
  @override
  void initState() {
    super.initState();
    // 设置 401 全局处理回调
    ApiClient.onUnauthorized = _handleUnauthorized;
    // 设置 403 LOGIN 禁用回调 — 强制下线
    ApiClient.onLoginDisabled = _handleLoginDisabled;
  }

  void _handleUnauthorized() {
    // 清除用户状态
    ref.read(userNotifierProvider.notifier).logout();
    // 跳转到登录页
    final router = ref.read(appRouterProvider);
    router.go(Routes.login);
  }

  void _handleLoginDisabled(String message) {
    // 清除用户状态（与 401 一样强制下线）
    ref.read(userNotifierProvider.notifier).logout();
    // 跳转到登录页
    final router = ref.read(appRouterProvider);
    router.go(Routes.login);
  }

  @override
  Widget build(BuildContext context) {
    final router = ref.watch(appRouterProvider);
    final themeMode = ref.watch(themeModeProvider);

    return MaterialApp.router(
      title: '股行',
      debugShowCheckedModeBanner: false,
      themeMode: themeMode,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: AppColors.primary,
          brightness: Brightness.light,
        ),
        scaffoldBackgroundColor: AppColors.background,
        useMaterial3: true,
        appBarTheme: const AppBarTheme(
          centerTitle: true,
          elevation: 0,
          backgroundColor: AppColors.surface,
          foregroundColor: AppColors.textPrimary,
        ),
        cardTheme: const CardThemeData(
          elevation: 2,
          color: AppColors.surface,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
        ),
        dividerTheme: const DividerThemeData(
          color: AppColors.divider,
        ),
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: AppColors.primary,
          brightness: Brightness.dark,
        ),
        scaffoldBackgroundColor: const Color(0xFF111827),
        useMaterial3: true,
        appBarTheme: const AppBarTheme(
          centerTitle: true,
          elevation: 0,
          backgroundColor: Color(0xFF1F2937),
          foregroundColor: Color(0xFFE5E7EB),
        ),
        cardTheme: const CardThemeData(
          elevation: 2,
          color: Color(0xFF1F2937),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
        ),
        dividerTheme: const DividerThemeData(
          color: Color(0xFF374151),
        ),
      ),
      routerConfig: router,
    );
  }
}
