import 'dart:async';
import 'dart:io';

import 'package:app_links/app_links.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/core/viewModels/PharmacyPagesViewModel.dart';
import 'package:hmg_patient_app/core/viewModels/dashboard_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/routes.dart';
import 'package:hmg_patient_app/services/payfort_services/payfort_view_model.dart';
import 'package:hmg_patient_app/services/robo_search/event_provider.dart';
import 'package:hmg_patient_app/services/robo_search/search_provider.dart';
import 'package:hmg_patient_app/theme/theme_notifier.dart';
import 'package:hmg_patient_app/theme/theme_value.dart';
import 'package:hmg_patient_app/uitl/DeepLinkHandler.dart';
import 'package:hmg_patient_app/uitl/PlatformBridge.dart';
import 'package:hmg_patient_app/uitl/navigation_service.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:localstorage/localstorage.dart';
import 'package:provider/provider.dart';

import 'config/size_config.dart';
import 'core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'core/viewModels/project_view_model.dart';
import 'locator.dart';
import 'pages/pharmacies/compare-list.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await initLocalStorage();

  // Pass all uncaught "fatal" errors from the framework to Crashlytics
  // FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;

  // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
  // PlatformDispatcher.instance.onError = (error, stack) {
  //   if (!kDebugMode) FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
  //   return true;
  // };

  setupLocator();
  HttpOverrides.global = MyHttpOverrides();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyApp createState() => new _MyApp();
}

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  }
}

class _MyApp extends State<MyApp> {
  // late AppUpdateInfo _updateInfo;
  StreamSubscription<Uri>? _linkSubscription;
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  //0537503378
  //1231755

  //0567184134 mobile
  //246305493

  // checkForUpdate() {
  //   // todo need to verify 'imp'
  //   InAppUpdate.checkForUpdate().then((info) {
  //     print("checkForUpdate!!!");
  //     print(info.toString());
  //     if (info.immediateUpdateAllowed) {
  //       print("Immediate567184134 Allowed!!!");
  //       InAppUpdate.performImmediateUpdate().then((value) {}).catchError((e) => print(e.toString()));
  //     }
  //   }).catchError((e) {
  //     print(e.toString());
  //   });
  // }

  @override
  void initState() {
    //ProjectViewModel projectProvider;
    // projectProvider = Provider.of(context);
    // var font = projectProvider.isArabic ? 'Cairo' : 'WorkSans';

    // Re-enable once going live
    // if (Platform.isAndroid) checkForUpdate();

    ThemeNotifier(defaultTheme());
    initDeepLinks();
    super.initState();
  }

  void dispose() {
    _linkSubscription?.cancel();

    super.dispose();
  }

  Future<void> initDeepLinks() async {
    // Handle links
    _linkSubscription = AppLinks().uriLinkStream.listen((uri) {
      debugPrint('onAppLink: $uri');
      openAppLink(uri);
    });
  }

  void openAppLink(Uri uri) {
    print("the uri is $uri");
    DeepLinkHandler.instance.handleDeepLinkAndNavigation(locator<NavigationService>().navigatorKey.currentState, uri, context);
  }

  @override
  Widget build(BuildContext context) {
    PlatformBridge.init(context);
    AppGlobal.context = context;

    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientationO.portraitDown,
    // ]);
    // final themeNotifier = Provider.of<ThemeNotifier>(context);
    precacheImage(AssetImage('assets/images/powerd-by.jpg'), context);

    return LayoutBuilder(
      builder: (context, constraints) {
        return OrientationBuilder(
          builder: (context, orientation) {
            SizeConfig().init(constraints, orientation);
            return MultiProvider(
              providers: [
                ChangeNotifierProvider<PharmacyPagesViewModel>(
                  create: (context) => PharmacyPagesViewModel(),
                ),
                ChangeNotifierProvider<ProjectViewModel>(
                  create: (context) => ProjectViewModel(),
                ),
                ChangeNotifierProvider<DashboardViewModel>(
                  create: (context) => DashboardViewModel(),
                ),
                ChangeNotifierProvider<ToDoCountProviderModel>(
                  create: (context) => ToDoCountProviderModel(),
                ),
                ChangeNotifierProvider<SearchProvider>(
                  create: (context) => SearchProvider(),
                ),
                ChangeNotifierProvider.value(
                  value: SearchProvider(),
                ),
                ChangeNotifierProvider<ThemeNotifier>(
                  create: (context) => ThemeNotifier(
                    defaultTheme(),
                  ),
                ),
                StreamProvider.value(
                  value: RobotProvider().intStream(),
                  initialData: RobotProvider().setValue({}),
                ),
                ChangeNotifierProvider<CompareList>(
                  create: (context) => CompareList(),
                ),
                ChangeNotifierProvider<OrderPreviewViewModel>(
                  create: (context) => OrderPreviewViewModel(),
                ),
                ChangeNotifierProvider<PayfortViewModel>(create: (context) => PayfortViewModel()),
              ],
              child: Consumer<ProjectViewModel>(
                builder: (context, projectProvider, child) => SafeArea(
                  top: false, // Set to true if you want to avoid the notch area as well
                  bottom: Platform.isIOS ? false : true,
                  child: MaterialApp(
                    builder: (context, mchild) {
                      AppGlobal.projectViewModelContext = context;
                      return MediaQuery(
                          data: MediaQuery.of(context).copyWith(
                            textScaler: TextScaler.linear(1.0),
                          ), //set desired text scale factor here
                          child: mchild!);
                    },
                    navigatorKey: locator<NavigationService>().navigatorKey,
                    showSemanticsDebugger: false,
                    title: 'Dr. AlHabib',
                    locale: projectProvider.appLocal,
                    localizationsDelegates: [
                      TranslationBaseDelegate(),
                      GlobalMaterialLocalizations.delegate,
                      GlobalWidgetsLocalizations.delegate,
                      GlobalCupertinoLocalizations.delegate,
                    ],
                    supportedLocales: [
                      const Locale('ar', ''), // Arabic
                      const Locale('en', ''), // English
                    ],
                    theme: Provider.of<ThemeNotifier>(context).getTheme(),
                    initialRoute: SPLASH,
                    // initialRoute: CALL_PAGE,
                    // initialRoute: OPENTOK_CALL_PAGE,
                    // initialRoute: PACKAGES_OFFERS,
                    // initialRoute: PACKAGES_ORDER_COMPLETED,
                    routes: routes,
                    debugShowCheckedModeBanner: false,
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
