import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'product/services/language_services.dart';
import 'feature/main/main_bloc.dart';
import 'product/base/bloc/base_bloc.dart';
import 'product/constant/navigation/navigation_router.dart';
import 'product/theme/provider/app_provider.dart';
import 'product/theme/theme_notifier.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    MultiProvider(
      providers: [...ApplicationProvider.instance.dependItems],
      child: BlocProvider(
        child: const MyApp(),
        blocBuilder: () => MainBloc(),
      ),
    ),
  );
}

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

  @override
  State<MyApp> createState() => _MyAppState();
  static void setLocale(BuildContext context, Locale newLocale) {
    _MyAppState? state = context.findAncestorStateOfType<_MyAppState>();
    state?.setLocale(newLocale);
  }
}

class _MyAppState extends State<MyApp> {
  Locale? _locale;
  late MainBloc mainBloc;
  LanguageServices languageServices = LanguageServices();
  // late ThemeNotifier themeNotifier;
  setLocale(Locale locale) {
    _locale = locale;
    mainBloc.sinkLanguage.add(_locale);
  }

  @override
  void initState() {
    super.initState();
    mainBloc = BlocProvider.of(context);
    // themeNotifier = Provider.of<ThemeNotifier>(context, listen: false);
    // ThemeNotifier().loadThemeFromPreferences();
    // log("ThemeKey1: ${LocaleManager.instance.getStringValue(PreferencesKeys.THEME)}");
    // log("Date: ${DateTime.parse("2024-11-16T07:17:36.785Z")}");
  }

  @override
  void didChangeDependencies() {
    languageServices.getLocale().then((locale) => {setLocale(locale)});
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final router = goRouter();
    return StreamBuilder<Locale?>(
      stream: mainBloc.streamLanguage,
      initialData: _locale,
      builder: (context, languageSnapshot) {
        return MaterialApp.router(
          theme: context.watch<ThemeNotifier>().currentTheme,
          routerConfig: router,
          localizationsDelegates: AppLocalizations.localizationsDelegates,
          supportedLocales: AppLocalizations.supportedLocales,
          locale: languageSnapshot.data,
        );
      },
    );
  }
}
