import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/hospitals/get_hospitals_response_model.dart';
import 'package:doctor_app_flutter/core/viewModel/authentication_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/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:provider/provider.dart';

import '../../widgets/shared/app_scaffold_widget.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  String? platformImei;
  bool allowCallApi = true;

  //TODO change AppTextFormField to AppTextFormFieldCustom
  final loginFormKey = GlobalKey<FormState>();
  var projectIdController = TextEditingController();
  var userIdController = TextEditingController();
  var passwordController = TextEditingController();
  List<GetHospitalsResponseModel> projectsList = [];
  FocusNode focusPass = FocusNode();
  FocusNode focusProject = FocusNode();
  late AuthenticationViewModel authenticationViewModel;
  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    authenticationViewModel = Provider.of<AuthenticationViewModel>(context);
    projectViewModel = Provider.of<ProjectViewModel>(context);
    return AppScaffold(
      isShowAppBar: false,
      backgroundColor: HexColor('#F8F8F8'),
      body: SafeArea(
        child: 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>[
                    //TODO Use App Text rather than text
                    Container(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(
                              height: 30,
                            ),
                          ],
                        ),
                        Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                          SizedBox(
                            height: 10,
                          ),
                          Text(
                            TranslationBase.of(context).welcomeTo,
                            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, fontFamily: 'Poppins'),
                          ),
                          Text(
                            TranslationBase.of(context).drSulaimanAlHabib,
                            style: TextStyle(color: Color(0xFF2B353E), fontWeight: FontWeight.bold, fontSize: SizeConfig.isMobile ? 24 : SizeConfig.realScreenWidth! * 0.029, fontFamily: 'Poppins'),
                          ),
                          Text(
                            "Doctor App",
                            style: TextStyle(fontSize: SizeConfig.isMobile ? 16 : SizeConfig.realScreenWidth! * 0.030, fontWeight: FontWeight.w600, color: Color(0xFFD02127)),
                          ),
                        ]),
                      ],
                    )),
                    SizedBox(
                      height: 40,
                    ),
                    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(),
                              AppTextFieldCustom(
                                hintText: TranslationBase.of(context).enterId,
                                hasBorder: true,
                                controller: userIdController,
                                onChanged: (value) {
                                  if (value != null)
                                    setState(() {
                                      authenticationViewModel.userInfo.userID = value.trim();
                                      authenticationViewModel.userInfo.memberID = value.trim();
                                    });
                                },
                                onFieldSubmitted: () {},
                              ),
                              buildSizedBox(),
                              AppTextFieldCustom(
                                hintText: TranslationBase.of(context).enterPassword,
                                hasBorder: true,
                                isSecure: true,
                                controller: passwordController,
                                onChanged: (value) {
                                  if (value != null) {
                                    setState(() {
                                      authenticationViewModel.userInfo.password = value.trim();
                                    });
                                    // if(allowCallApi) {
                                    this.getProjects(authenticationViewModel.userInfo.userID);
                                    //   setState(() {
                                    //     allowCallApi = false;
                                    //   });
                                    // }
                                  }
                                },
                                onClick: () {},
                                onFieldSubmitted: () {},
                              ),
                              buildSizedBox(),
                              AppTextFieldCustom(
                                hintText: TranslationBase.of(context).selectYourProject,
                                hasBorder: true,
                                controller: projectIdController,
                                isTextFieldHasSuffix: true,
                                enabled: false,
                                onClick: () {
                                  Utils.showCupertinoPicker(context, projectsList, 'facilityName', onSelectProject, authenticationViewModel);
                                },
                                onChanged: (value) {},
                                onFieldSubmitted: () {},
                              ),
                              buildSizedBox()
                            ]),
                          ),
                        ],
                      ),
                    )
                  ],
                )
              ]))
        ]),
      ),
      bottomSheet: Container(
        height: 90,
        width: double.infinity,
        child: Center(
          child: FractionallySizedBox(
            widthFactor: 0.9,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                AppButton(
                  title: TranslationBase.of(context).login,
                  color: AppGlobal.appRedColor,
                  fontWeight: FontWeight.w600,
                  disabled: authenticationViewModel.userInfo.userID == null || authenticationViewModel.userInfo.password == null,
                  onPressed: () {
                    login(context);
                  },
                ),
                SizedBox(
                  height: 25,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

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

  login(
    context,
  ) async {
    if (loginFormKey.currentState!.validate()) {
      loginFormKey.currentState!.save();
      GifLoaderDialogUtils.showMyDialog(context);
      await authenticationViewModel.login(authenticationViewModel.userInfo);
      if (authenticationViewModel.state == ViewState.ErrorLocal) {
        GifLoaderDialogUtils.hideDialog(context);
        Utils.showErrorToast(authenticationViewModel.error);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        // authenticationViewModel.setUnverified(true, isFromLogin: true);
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (BuildContext context) =>
                VerificationMethodsScreen(
                  password: authenticationViewModel.userInfo.password,
                   isMoreOption: true,
                   // isFromLogin: true,
            ),
          ),
         );
      }
    }
  }

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

    primaryFocus!.unfocus();
  }

  String memberID = "";

  getProjects(memberID) async {
    if (memberID != null && memberID != '') {
      if (this.memberID != memberID) {
        this.memberID = memberID;
        await authenticationViewModel.getHospitalsList(memberID);
        if (authenticationViewModel.state == ViewState.Idle) {
          projectsList = authenticationViewModel.hospitals;
          setState(() {
            projectViewModel.setVidaPlusProjectList(authenticationViewModel.vidaPlusProjectList);
            if(projectsList.isNotEmpty) {
              authenticationViewModel.userInfo.projectID = projectsList.first.facilityId;
              projectIdController.text = projectsList.first.facilityName!;
            }
          });
        }
      }
    }
  }
}
