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

import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/core/service/auth_service.dart';
import 'package:doctor_app_flutter/core/viewModel/imei_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/screens/auth/verification_methods_screen.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/widgets/shared/app_loader_widget.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../lookups/auth_lookup.dart';
import '../../util/dr_app_shared_pref.dart';
import '../../widgets/auth/auth_header.dart';
import '../../widgets/auth/login_form.dart';
import '../../widgets/shared/app_scaffold_widget.dart';

DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();

class Loginsreen extends StatefulWidget {
  @override
  _LoginsreenState createState() => _LoginsreenState();
}

class _LoginsreenState extends State<Loginsreen> {
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  String platformImei;
  // Future<String> platformImeiFuture;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  bool _isLoading = true;
  ProjectViewModel projectViewModel;
  AuthService authService = AuthService();
  @override
  void initState() {
    super.initState();

    _firebaseMessaging.setAutoInitEnabled(true);
    if (Platform.isIOS) {
      _firebaseMessaging.requestNotificationPermissions();
    }

    _firebaseMessaging.getToken().then((String token) async {
      if (DEVICE_TOKEN == "" && projectViewModel.isLogin == false) {
        DEVICE_TOKEN = token;
        changeLoadingStata(true);
        authService.selectDeviceImei(DEVICE_TOKEN).then((value) {
          print(authService.dashboardItemsList);

          if (authService.dashboardItemsList.length > 0) {
            sharedPref.setObj(
                LAST_LOGIN_USER, authService.dashboardItemsList[0]);
            Navigator.of(context).pushReplacement(MaterialPageRoute(
                builder: (BuildContext context) => VerificationMethodsScreen(
                      password: null,
                    )));
          } else {
            changeLoadingStata(false);
          }
          //changeLoadingStata(false);
        });
      } else {
        changeLoadingStata(false);
      }

      // else if (projectViewModel.isLogin) {
      //   getNotificationCount(token);
      // }
    }).catchError((err) {
      print(err);
    });
  }

/*
 *@author: Elham Rababah
 *@Date:19/4/2020
 *@param: isLoading
 *@return:
 *@desc:   Change Isloading attribute in order to show or hide loader
 */
  void changeLoadingStata(isLoading) {
    setState(() {
      _isLoading = isLoading;
    });
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of<ProjectViewModel>(context);

    return BaseView<IMEIViewModel>(
        onModelReady: (model) => {},
        builder: (_, model, w) => AppScaffold(
              baseViewModel: model,
              isShowAppBar: false,
              backgroundColor: HexColor('#F8F8F8'),
              body: SafeArea(
                child: (_isLoading == false)
                    ? ListView(children: <Widget>[
                        Container(
                            margin:
                                EdgeInsetsDirectional.fromSTEB(30, 0, 30, 30),
                            alignment: Alignment.topLeft,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      AuthHeader(loginType.knownUser),
                                      SizedBox(
                                        height: 40,
                                      ),
                                      LoginForm(
                                        model: model,
                                      ),
                                    ],
                                  )
                                ]))
                      ])
                    : Center(child: AppLoaderWidget()),
              ),
            ));
  }
}
