import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/viewModel/imei_view_model.dart';
import 'package:doctor_app_flutter/screens/auth/verification_methods_screen.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app_text_form_field.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:provider/provider.dart';

import '../../config/shared_pref_kay.dart';
import '../../config/size_config.dart';
import '../../core/viewModel/hospital_view_model.dart';
import '../../models/doctor/user_model.dart';
import '../../util/dr_app_shared_pref.dart';
import '../../util/dr_app_toast_msg.dart';
import '../../util/helpers.dart';

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

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

  final IMEIViewModel model;

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

class _LoginFormState extends State<LoginForm> {
  final loginFormKey = GlobalKey<FormState>();
  var projectIdController = TextEditingController();
  var projectsList = [];
  FocusNode focusPass = FocusNode();
  FocusNode focusProject = FocusNode();
  HospitalViewModel projectsProv;
  var userInfo = UserModel();
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectsProv = Provider.of<HospitalViewModel>(context);
    return Form(
      key: loginFormKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: SizeConfig.realScreenWidth * 0.90,
            height: SizeConfig.realScreenHeight * 0.65,
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              buildSizedBox(),
              Padding(
                  child: AppText(
                    TranslationBase.of(context).enterCredentials,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                  padding: EdgeInsets.only(top: 10, bottom: 10)),
              Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(6.0)),
                      border: Border.all(
                        width: 1.0,
                        color: HexColor("#CCCCCC"),
                      ),
                      color: Colors.white),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                            padding: EdgeInsets.only(left: 10, top: 10),
                            child: AppText(
                              TranslationBase.of(context).enterId,
                              fontWeight: FontWeight.w800,
                              fontSize: 14,
                            )),
                        AppTextFormField(
                          labelText: '',
                          borderColor: Colors.white,
                          // keyboardType: TextInputType.number,
                          textInputAction: TextInputAction.next,

                          validator: (value) {
                            if (value != null && value.isEmpty) {
                              return TranslationBase.of(context)
                                  .pleaseEnterYourID;
                            }
                            return null;
                          },
                          onSaved: (value) {
                            if (value != null) userInfo.userID = value.trim();
                          },
                          onChanged: (value) {
                            if (value != null) userInfo.userID = value.trim();
                          },
                          onFieldSubmitted: (_) {
                            focusPass.nextFocus();
                          },
                        )
                      ])),
              buildSizedBox(),
              Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(6.0)),
                      border: Border.all(
                        width: 1.0,
                        color: HexColor("#CCCCCC"),
                      ),
                      color: Colors.white),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                            padding: EdgeInsets.only(left: 10, top: 10),
                            child: AppText(
                              TranslationBase.of(context).enterPassword,
                              fontWeight: FontWeight.w800,
                              fontSize: 14,
                            )),
                        AppTextFormField(
                          focusNode: focusPass,
                          obscureText: true,
                          borderColor: Colors.white,
                          textInputAction: TextInputAction.next,
                          validator: (value) {
                            if (value != null && value.isEmpty) {
                              return TranslationBase.of(context)
                                  .pleaseEnterPassword;
                            }
                            return null;
                          },
                          onSaved: (value) {
                            userInfo.password = value;
                          },
                          onFieldSubmitted: (_) {
                            focusPass.nextFocus();
                            Helpers.showCupertinoPicker(context, projectsList,
                                'facilityName', onSelectProject);
                          },
                          onTap: () {
                            this.getProjects(userInfo.userID);
                          },
                        )
                      ])),
              buildSizedBox(),
              projectsList.length > 0
                  ? Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(6.0)),
                          border: Border.all(
                            width: 1.0,
                            color: HexColor("#CCCCCC"),
                          ),
                          color: Colors.white),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                                padding: EdgeInsets.only(left: 10, top: 10),
                                child: AppText(
                                  TranslationBase.of(context).selectYourProject,
                                  fontWeight: FontWeight.w600,
                                )),
                            AppTextFormField(
                                focusNode: focusProject,
                                controller: projectIdController,
                                borderColor: Colors.white,
                                suffixIcon: Icons.arrow_drop_down,
                                onTap: () {
                                  Helpers.showCupertinoPicker(
                                      context,
                                      projectsList,
                                      'facilityName',
                                      onSelectProject);
                                },
                                validator: (value) {
                                  if (value != null && value.isEmpty) {
                                    return TranslationBase.of(context)
                                        .pleaseEnterYourProject;
                                  }
                                  return null;
                                })
                          ]))
                  : Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(6.0)),
                          border: Border.all(
                            width: 1.0,
                            color: HexColor("#CCCCCC"),
                          ),
                          color: Colors.white),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                                padding: EdgeInsets.only(left: 10, top: 10),
                                child: AppText(
                                  TranslationBase.of(context).selectYourProject,
                                  fontWeight: FontWeight.w800,
                                  fontSize: 14,
                                )),
                            AppTextFormField(
                              readOnly: true,
                              borderColor: Colors.white,
                              prefix: IconButton(
                                icon: Icon(Icons.arrow_drop_down),
                                iconSize: 30,
                                padding: EdgeInsets.only(bottom: 30),
                              ),
                            )
                          ])),
            ]),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Expanded(
                  child: AppButton(
                title: TranslationBase.of(context).login,
                color: HexColor('#D02127'),
                fontWeight: FontWeight.bold,
                onPressed: () {
                  login(context, this.widget.model);
                },
              )),
            ],
          )
        ],
      ),
    );
    //));
  }

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

  login(
    context,
    model,
  ) {
    if (loginFormKey.currentState.validate()) {
      loginFormKey.currentState.save();
      sharedPref.setInt(PROJECT_ID, userInfo.projectID);
      model.login(userInfo).then((res) {
        if (model.loginInfo['MessageStatus'] == 1) {
          saveObjToString(LOGGED_IN_USER, model.loginInfo);
          sharedPref.remove(LAST_LOGIN_USER);
          sharedPref.setString(TOKEN, model.loginInfo['LogInTokenID']);
          Navigator.of(AppGlobal.CONTEX).pushReplacement(MaterialPageRoute(
              builder: (BuildContext context) => VerificationMethodsScreen(
                    password: userInfo.password,
                  )));
        }
      });
    }
  }

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

  getProjectsList(memberID) {
    projectsProv.getProjectsList(memberID).then((res) {
      if (res['MessageStatus'] == 1) {
        projectsList = res['ProjectInfo'];
        setState(() {
          userInfo.projectID = projectsList[0]["facilityId"];
          projectIdController.text = projectsList[0]['facilityName'];
        });
      } else {
        print(res);
      }
    });
  }

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

  onSelectProject(index) {
    setState(() {
      userInfo.projectID = projectsList[index]["facilityId"];
      projectIdController.text = projectsList[index]['facilityName'];
    });

    primaryFocus.unfocus();
  }

  getProjects(value) {
    if (value != null && value != '') {
      if (projectsList.length == 0) {
        getProjectsList(value);
      }
    }
  }
}
