import 'package:food_delivery_client/feature/common/presentation/blocs/theme_bloc/theme_bloc.dart';
import 'package:toastification/toastification.dart';
import 'food_delivery_client.dart';

void main() {
  runZonedGuarded(
    () async {
      WidgetsFlutterBinding.ensureInitialized();
      FlutterError.onError = (details) {
        FlutterError.presentError(details);
        log("Flutter.onError $details");
      };
      Bloc.observer = AppBlocObserver();
      await configureDependencies();
      runApp(
        MultiBlocProvider(
          providers: [
            BlocProvider(create: (context) => sl<LanguageBloc>()),
            BlocProvider(create: (context) => sl<ThemeBloc>()),
          ],
          child: MyApp(),
        ),
      );
    },
    (error, stack) {
      log("RunZoneGuard Error $error");
    },
  );
}

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

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      context.read<LanguageBloc>().add(LanguageEvent.started());
      context.read<ThemeBloc>().add(ThemeEvent.started());
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LanguageBloc, LanguageState>(
      builder: (context, state) {
        return BlocBuilder<ThemeBloc, ThemeState>(
          builder: (context, themeState) {
            return ToastificationWrapper(
              child: MaterialApp.router(
                title: AppLocaleKeys.appName,
                debugShowCheckedModeBanner: false,
                theme: AppTheme.lightTheme,
                darkTheme: AppTheme.darkTheme,
               themeMode: ThemeMode.light,
               // themeMode: themeState.themeMode,
                routerConfig: sl<AppRoutes>().router,
                locale: state.currentLocale,
                supportedLocales: L10n.locales,
                localizationsDelegates: [
                  AppLocalizations.delegate,
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                builder: (context, child) => GestureDetector(
                  onTap: () {
                    FocusManager.instance.primaryFocus?.unfocus();
                  },
                  child: MediaQuery(
                    data: MediaQuery.of(
                      context,
                    ).copyWith(textScaler: const TextScaler.linear(1)),
                    child: child!,
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
