import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:local_auth/local_auth.dart';
import 'package:tanami_app/Globalconst.dart';
import 'package:tanami_app/features/login/presentation/bloc/login_bloc.dart';

import 'core/routes/routes.dart';
import 'core/utils/connectivity/network_connectivity.dart';
import 'core/utils/language/localizations_delegate.dart';
import 'core/utils/secure/secure_storage_service.dart';
import 'features/biometric/bloc/biometric_bloc.dart';
import 'features/biometric/bloc/biometric_event.dart';
import 'features/countrySelection/bloc/GetCountry/get_country_bloc.dart';
import 'features/countrySelection/bloc/choose_country_bloc.dart';
import 'features/forgotPassword/presentation/bloc/restore_password_phone_verification_bloc.dart';
import 'features/languageChange/presentation/bloc/text_bloc/text_bloc.dart';
import 'features/otpVerification/bloc/otp_bloc.dart';
import 'features/register/presentation/bloc/register_bloc.dart';
import 'shared/components/bloc/bottom_nav_bar/bottom_navigation_bloc.dart';
import 'shared/components/bloc/language/lng_bloc.dart';
import 'shared/components/bloc/language/lng_event.dart';
import 'shared/components/bloc/language/lng_state.dart';

/* CREATED BY - JAYESH JAIN 
   DATE - 24-05-2024 
 */

/// The main function that runs the application.
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // FlutterError.onError = (FlutterErrorDetails details) {
  //   FlutterError.dumpErrorToConsole(details);
  //   runApp(CustomErrorWidget(
  //     errorMessage: details.toString(),
  //   ));
  // };
// Set the preferred orientations of the device.
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]).then((value) => runApp(const MyApp()
      // StatsFl(
      //     isEnabled: true, //Toggle on/off
      //     width: 200, //Set size
      //     height: 50, //
      //     maxFps: 60, // Support custom FPS target (default is 60)
      //     showText: true, // Hide text label
      //     sampleTime: .5, //Interval between fps calculations, in seconds.
      //     totalTime: 15, //Total length of timeline, in seconds.
      //     align: Alignment.center, //Alignment of statsbox
      //     child: const MyApp()
      ));
}

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

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final SharedPreferenceLocalData secureStorageService =
      SharedPreferenceLocalData();
  final NetworkConnectivity _networkConnectivity =
      NetworkConnectivity(onStatusChange: (_) {});
  String languageSelected = "";
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    changeLanguage();
    // Initialize the NetworkConnectivity instance.
    _networkConnectivity.initialize();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _networkConnectivity.dispose();
    super.dispose();
  }

  Future changeLanguage() async {
    languageSelected =
        (await secureStorageService.read("languageSelected")) ?? "";
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (_) => LocalizationBloc(),
        ),
        BlocProvider(
          create: (context) => RadioBloc(),
        ),
        BlocProvider(
          create: (_) => BottomNavigationBloc(),
        ),
        BlocProvider(
          create: (_) =>
              RegisterBloc(secureStorageService: secureStorageService),
        ),
        BlocProvider(
          create: (_) => LoginBloc(secureStorageService: secureStorageService),
        ),
        BlocProvider(
          create: (_) => BiometricBloc(
            LocalAuthentication(),
            secureStorageService,
          )..add(CheckBiometricEvent()),
        ),
        BlocProvider(
          create: (_) => LocalizationBloc(),
        ),
        BlocProvider(
          create: (_) => GetCountryBlock(),
        ),
        BlocProvider(
          create: (_) => OTPBloc(),
        ),
        BlocProvider(
          create: (_) => RestorePasswordPhoneVerificationBloc(
              secureStorageService: secureStorageService),
        ),
        BlocProvider(
          create: (_) => TextLanguageBloc(),
        )
      ],
      child: ScreenUtilInit(
        builder: (BuildContext context, Widget? child) =>
            BlocBuilder<LocalizationBloc, LocalizationState>(
                builder: (context, state) {
          changeLanguage().then(
            (value) {
              if (languageSelected.isEmpty) {
                context
                    .read<LocalizationBloc>()
                    .add(const ChangeLanguage(Locale('en')));
                Globalconst.languageSelected = "en";
              } else if (languageSelected == "en") {
                context
                    .read<LocalizationBloc>()
                    .add(const ChangeLanguage(Locale('en')));
                Globalconst.languageSelected = "en";
              } else {
                context
                    .read<LocalizationBloc>()
                    .add(const ChangeLanguage(Locale('ar')));
                Globalconst.languageSelected = "ar";
              }
            },
          );

          return MaterialApp.router(
            title: 'Tanami Capital',
            locale: state.locale,
            supportedLocales: const [
              Locale('en', ''),
              Locale('ar', ''),
            ],
            localizationsDelegates: const [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            localeResolutionCallback: (locale, supportedLocales) {
              for (var supportedLocale in supportedLocales) {
                if (supportedLocale.languageCode == locale?.languageCode) {
                  return supportedLocale;
                }
              }
              return supportedLocales.first;
            },
            theme: ThemeData(
              useMaterial3: true,
            ),
            debugShowCheckedModeBanner: false,
            routerConfig: goRouter,
          );
        }),
        designSize: const Size(390, 844),
      ),
    );
  }
}
