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

import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/pages/BookAppointment/SearchResultsByRegion.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.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/LocalNotification.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/push-notification-handler.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_zoom_videosdk/native/zoom_videosdk.dart';
import 'package:provider/provider.dart';

import 'core/service/AuthenticatedUserObject.dart';
import 'core/service/privilege_service.dart';
import 'core/viewModels/project_view_model.dart';
import 'locator.dart';

AppSharedPreferences sharedPref = new AppSharedPreferences();
AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  PrivilegeService _privilegeService = locator<PrivilegeService>();

  @override
  void initState() {
    AppGlobal.context = context;
    super.initState();
    print("Splash init called.............");
    Timer(
      Duration(seconds: 1, milliseconds: 500),
      () async {
        await loadPrivilege().then((value) {
          LocalNotification.init(onNotificationClick: (payload) {});
          // LocalNotification.getInstance().showNow(title: "Payload", subtitle: "Subtitle", payload: "Payload");
          if (!_privilegeService.hasError) {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(
                builder: (BuildContext context) => LandingPage(),
              ),
            );
          } else {}
        });
      },
    );

    var zoom = ZoomVideoSdk();
    InitConfig initConfig = InitConfig(
      domain: "zoom.us",
      enableLog: true,
    );
    zoom.initSdk(initConfig);

    // AppSharedPreferences().getAll().then((value) {
    //   debugPrint("ALL SHARED PREFERENCES!!!!!");
    //   debugPrint(jsonEncode(value));
    // });
  }

  /// load the Privilege from service
  Future loadPrivilege() async {
    await _privilegeService.getPrivilege();
    ProjectViewModel projectProvider = Provider.of<ProjectViewModel>(context, listen: false);
    projectProvider.setPrivilegeModelList(privilege: _privilegeService.privilegeModelList);
    projectProvider.setVidaPlusProjectList(_privilegeService.vidaPlusProjectListModel);
    projectProvider.setHMCProjectList(_privilegeService.hMCProjectListModel);
    projectProvider.setProjectsDetailList(_privilegeService.projectDetailListModel);
    double lat = await AppSharedPreferences().getDouble(USER_LAT) ?? 0.0;
    double long = await AppSharedPreferences().getDouble(USER_LONG) ?? 0.0;
    AppSharedPreferences().clear(); // Clearing Shared Preferences On App Launch
    await AppSharedPreferences().setDouble(USER_LAT, lat);
    await AppSharedPreferences().setDouble(USER_LONG, long);
    AppSharedPreferences().setString(APP_LANGUAGE, projectProvider.isArabic ? "ar" : "en");
    var themeNotifier = Provider.of<ThemeNotifier>(context, listen: false);
    themeNotifier.setTheme(defaultTheme(fontName: projectProvider.isArabic ? 'Cairo' : 'Poppins'));
    PushNotificationHandler().init(context); // Asyncronously
    AppSharedPreferences().getAll().then((value) {
      // debugPrint("ALL SHARED PREFERENCES!!!!!");
      // debugPrint(jsonEncode(value));
    });
    // if (!kDebugMode) await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
    // PushNotificationHandler(context).init(); // Asyncronously
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffF8F8F8),
      body: Stack(
        alignment: Alignment.center,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 53),
            child: Image.asset(
              'assets/images/new/hmg_logo.png',
              fit: BoxFit.fitWidth,
              width: MediaQuery.of(context).size.width,
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  TranslationBase.of(context).poweredBy,
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: Color(0xff333C45), letterSpacing: -0.56, height: 16 / 14),
                ),
                SizedBox(
                  height: 5,
                ),
                SvgPicture.asset(
                  'assets/images/new/cloud_logo.svg',
                  width: 40,
                  height: 40,
                ),
                SizedBox(
                  height: 7,
                ),
                // Text(
                //   "Version 1.1.0",
                //   style: TextStyle(fontSize: 10, fontWeight: FontWeight.w400, color: Color(0xff3989898), letterSpacing: 0, height: 12 / 10),
                // ),
                SizedBox(
                  height: 18,
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
