import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'core/theme/app_colors.dart';
import 'core/theme/app_theme.dart';
import 'core/theme/theme_mode_provider.dart';
import 'core/theme/tdesign_resource_delegate.dart';
import 'core/router/app_router.dart';
import 'core/network/api_client.dart';
import 'core/auth/auth_service.dart';
import 'core/i18n/app_localizations.dart';
import 'core/i18n/locale_provider.dart';
import 'core/navigation/navigation_channel.dart';
import 'core/navigation/host_app_channel.dart';

final apiClientProvider = Provider<ApiClient>((ref) {
  const useMock = true;
  final client = ApiClient(
    baseUrl: HostAppChannel.baseUrl,
    useMock: useMock,
  );
  final authService = ref.read(authServiceProvider);
  client.setToken(authService.token);
  return client;
});

final authServiceProvider = Provider<AuthService>((ref) => AuthService());

final _routerProvider = Provider<GoRouter>((ref) => createAppRouter());

class App extends ConsumerWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final router = ref.watch(_routerProvider);
    final locale = ref.watch(localeProvider);
    final themeMode = ref.watch(themeModeProvider);

    // 监听平台（iOS）下发的导航指令
    NavigationChannel.startListening(router);

    TDTheme.needMultiTheme();
    TDTheme.setResourceBuilder(
      (context) => TDResourceI18nDelegate(context),
      needAlwaysBuild: true,
    );
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(
        statusBarColor: AppColors.bgCard,
        statusBarIconBrightness: Brightness.dark,
      ),
      child: MaterialApp.router(
        key: ValueKey(locale),
        title: 'TBOSS OA',
        theme: AppTheme.light,
        darkTheme: AppTheme.dark,
        themeMode: themeMode,
        routerConfig: router,
        locale: locale,
        supportedLocales: const [
          Locale('zh', 'CN'),
          Locale('en'),
          Locale('zh', 'TW'),
        ],
        localizationsDelegates: const [
          AppLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        debugShowCheckedModeBanner: false,
      ),
    );
  }
}
