import 'package:doctor_app_flutter/lookups/hospital_lookup.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:imei_plugin/imei_plugin.dart';
import 'package:provider/provider.dart';

import '../../config/shared_pref_kay.dart';
import '../../config/size_config.dart';
import '../../models/doctor/user_model.dart';
import '../../providers/auth_provider.dart';
import '../../providers/hospital_provider.dart';
import '../../routes.dart';
import '../../util/dr_app_shared_pref.dart';
import '../../util/dr_app_toast_msg.dart';
import '../../util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';

DrAppSharedPreferances sharedPref = DrAppSharedPreferances();
DrAppToastMsg toastMsg = DrAppToastMsg();
Helpers helpers = Helpers();

class LoginForm extends StatefulWidget with DrAppToastMsg {
  LoginForm({this.changeLoadingStata});

  final Function changeLoadingStata;

  @override
  _LoginFormState createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final loginFormKey = GlobalKey<FormState>();
  var projectIdController = TextEditingController();
  String _platformImei = 'Unknown';
  String uniqueId = "Unknown";
  var projectsList = [];
  bool _isInit = true;
  FocusNode focusPass = FocusNode();
  FocusNode focusProject = FocusNode();

  var userInfo = UserModel(
      UserID: '',
      Password: '',
      ProjectID: 15,
      LanguageID: 2,
      IPAdress: "11.11.11.11",
      VersionID: 1.2,
      Channel: 9,
      SessionID: "i1UJwCTSqt");

  AuthProvider authProv;
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    authProv = Provider.of<AuthProvider>(context);

    if (_isInit) {
      if (projectsList.length == 0) {
        getProjectsList();
      }
    }
    _isInit = false;
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: loginFormKey,
      child: Container(
        width: SizeConfig.realScreenWidth * 0.90,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildSizedBox(),
            TextFormField(
              keyboardType: TextInputType.number,
              textInputAction: TextInputAction.next,
              decoration: buildInputDecoration(
                  context,
                  TranslationBase.of(context).enterId,
                  'assets/images/user_id_icon.png'),
              validator: (value) {
                if (value.isEmpty) {
                  return TranslationBase.of(context).pleaseEnterYourID;
                }
                return null;
              },
              onSaved: (value) {
                userInfo.UserID = value.trim();
              },
              onFieldSubmitted: (_) {
                focusPass.nextFocus();
              },
              autofocus: false,
            ),
            buildSizedBox(),
            TextFormField(
              focusNode: focusPass,
              obscureText: true,
              textInputAction: TextInputAction.next,
              decoration: buildInputDecoration(
                  context,
                  TranslationBase.of(context).enterPassword,
                  'assets/images/password_icon.png'),
              validator: (value) {
                if (value.isEmpty) {
                  return TranslationBase.of(context).pleaseEnterPassword;
                }
                return null;
              },
              onSaved: (value) {
                userInfo.Password = value;
              },
              onFieldSubmitted: (_) {
                focusPass.nextFocus();
                helpers.showCupertinoPicker(
                    context, projectsList, 'Name', onSelectProject);
              },
            ),
            buildSizedBox(),
            TextFormField(
                focusNode: focusProject,
                controller: projectIdController,
                onTap: () {
                  helpers.showCupertinoPicker(
                      context, projectsList, 'Name', onSelectProject);
                },
                showCursor: false,
                readOnly: true,
                decoration: buildInputDecoration(
                    context,
                    TranslationBase.of(context).selectYourProject,
                    'assets/images/password_icon.png'),
                validator: (value) {
                  if (value.isEmpty) {
                    return TranslationBase.of(context).pleaseEnterYourProject;
                  }
                  return null;
                }),
            buildSizedBox(),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                RaisedButton(
                  onPressed: () {
                    login(context, authProv, widget.changeLoadingStata);
                  },
                  textColor: Colors.white,
                  elevation: 0.0,
                  padding: const EdgeInsets.all(0.0),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                      side: BorderSide(width: 0.5, color: Hexcolor('#CCCCCC'))),
                  child: Container(
                    padding: const EdgeInsets.all(10.0),
                    height: 50,
                    width: SizeConfig.realScreenWidth * 0.35,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(TranslationBase.of(context).login,
                            style: TextStyle(
                                fontSize: SizeConfig.isMobilePortrait
                                    ? 2.3 * SizeConfig.textMultiplier
                                    : 2.3 * SizeConfig.textMultiplier)),
                        Image.asset('assets/images/login_btn_arrow_icon.png')
                      ],
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

/*
 *@author: Elham Rababah
 *@Date:20/4/2020
 *@param: context, hint, asset
 *@return: InputDecoration
 *@desc:   decorate input feilds
 */
  InputDecoration buildInputDecoration(BuildContext context, hint, asset) {
    return InputDecoration(
      prefixIcon: Image.asset(asset),
      hintText: hint,
      hintStyle: TextStyle(fontSize: 2 * SizeConfig.textMultiplier),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        borderSide: BorderSide(color: Hexcolor('#CCCCCC')),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).primaryColor),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Theme.of(context).errorColor),
      ),
    );
  }

  SizedBox buildSizedBox() {
    return SizedBox(
      height: 20,
    );
  }

  login(context, AuthProvider authProv, Function changeLoadingStata) {
    FocusScopeNode currentFocus = FocusScope.of(context);

    // if (!currentFocus.hasPrimaryFocus) {
    //   currentFocus.unfocus();
    // }
    changeLoadingStata(true);
    if (loginFormKey.currentState.validate()) {
      loginFormKey.currentState.save();
      sharedPref.setInt(PROJECT_ID, userInfo.ProjectID);
      authProv.login(userInfo).then((res) {
        changeLoadingStata(false);

        if (res['MessageStatus'] == 1) {
          // insertDeviceImei(res, authProv);
          saveObjToString('loggedUser', res);
          sharedPref.setString(TOKEN, res['LogInTokenID']);
          print("token" + res['LogInTokenID']);

          Navigator.of(context).pushReplacementNamed(VERIFICATION_METHODS);
        } else {
          // handel error
          // widget.showCenterShortLoadingToast("watting");
          helpers.showErrorToast(res['ErrorEndUserMessage']);
        }
        // Navigator.of(context).pushNamed(HOME);
      }).catchError((err) {
        print('$err');
        changeLoadingStata(false);
        helpers.showErrorToast(err);
      });
    } else {
      changeLoadingStata(false);
    }
  }

  insertDeviceImei(preRes, AuthProvider authProv) {
    if (_platformImei != 'Unknown') {
      var imeiInfo = {
        "IMEI": _platformImei,
        "LogInType": 1,
        "DoctorID": preRes['DoctorID'],
        "DoctorName": "Test User",
        "Gender": 1,
        "ClinicID": 3,
        "ProjectID": 15,
        "DoctorTitle": "Mr.",
        "ClinicName": "MED",
        "ProjectName": "",
        "DoctorImageURL": "UNKNOWN",
        "LogInTokenID": preRes['LogInTokenID'],
        "VersionID": 1.2
      };
      authProv.insertDeviceImei(imeiInfo).then((res) {
        if (res['MessageStatus'] == 1) {
          setSharedPref('platformImei', _platformImei);
          saveObjToString('loggedUser', preRes);
          Navigator.of(context).pushNamed(VERIFICATION_METHODS);
          // save imei on shared preferance
        } else {
          // handel error
          helpers.showErrorToast(res['ErrorEndUserMessage']);
        }
      }).catchError((err) {
        print(err);
        helpers.showErrorToast();
      });
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformImei;
    String idunique;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformImei =
          await ImeiPlugin.getImei(shouldShowRequestPermissionRationale: false);
      idunique = await ImeiPlugin.getImei();
    } catch(e) {
      platformImei = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformImei = platformImei;
      uniqueId = idunique;
    });
  }

  Future<void> setSharedPref(key, value) async {
    sharedPref.setString(key, value).then((success) {
      print("sharedPref.setString" + success.toString());
    });
  }

  getProjectsList() {
    HospitalProvider projectsProv = Provider.of<HospitalProvider>(context);
    projectsProv.getProjectsList().then((res) {
      if (res['MessageStatus'] == 1) {
        setState(() {
          projectsList = res['ListProject'];
        });
      } else {
        // handel error
        setState(() {
          projectsList = ListProject;
        });
      }
    }).catchError((err) {
      setState(() {
        projectsList = ListProject;
      });
      print(err);
    });
  }

  saveObjToString(String key, value) async {
    sharedPref.setObj(key, value);
  }

  onSelectProject(index) {
    setState(() {
      userInfo.ProjectID = projectsList[index]["ID"];
      projectIdController.text = projectsList[index]['Name'];
    });

    primaryFocus.unfocus();
  }
}
