import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.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/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.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> {
  late String platformImei;
  bool allowCallApi = true;

  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;

  @override
  Widget build(BuildContext context) {
    authenticationViewModel = Provider.of<AuthenticationViewModel>(context);
    double textFieldHeight = SizeConfig.heightMultiplier * (SizeConfig.isHeightVeryShort ?10:SizeConfig.isHeightShort?8:6);
    return AppScaffold(
      isShowAppBar: false,
      backgroundColor: HexColor('#F8F8F8'),
      body: SingleChildScrollView(
        child: SafeArea(
          child: Container(
              margin: EdgeInsetsDirectional.fromSTEB(30, 0, 30, 30),
              alignment: Alignment.topLeft,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  //TODO Use App Text rather than text
                  Container(
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              TranslationBase.of(context).welcomeTo??"",
                              style: TextStyle(
                                  fontSize: SizeConfig
                                          .getTextMultiplierBasedOnWidth() *
                                      4,
                                  fontWeight: FontWeight.w600,
                                  fontFamily: 'Poppins'),
                            ),
                            Text(
                              TranslationBase.of(context).drSulaimanAlHabib!,
                              style: TextStyle(
                                  color: Color(0xFF2B353E),
                                  fontWeight: FontWeight.bold,
                                  fontSize: SizeConfig
                                          .getTextMultiplierBasedOnWidth() *
                                      6,
                                  fontFamily: 'Poppins'),
                            ),
                            Text(
                              "Doctor App",
                              style: TextStyle(
                                  fontSize: SizeConfig
                                          .getTextMultiplierBasedOnWidth() *
                                      4,
                                  fontWeight: FontWeight.w600,
                                  color: Color(0xFFD02127)),
                            ),
                          ])),
                  SizedBox(
                    height: 40,
                  ),
                  Form(
                    key: loginFormKey,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          buildSizedBox(),
                          AppTextFieldCustom(
                            height: textFieldHeight,
                            hintText: TranslationBase.of(context).enterId,
                            hasBorder: true,
                            controller: userIdController,
                            onChanged: (value) {
                              if (value != null)
                                setState(() {
                                  authenticationViewModel.userInfo.userID =
                                      value.trim();
                                });
                            },
                          ),
                          buildSizedBox(),
                          AppTextFieldCustom(
                            height: textFieldHeight,
                            hintText: TranslationBase.of(context).enterPassword,
                            hasBorder: true,
                            isSecure: true,
                            controller: passwordController,
                            onChanged: (value) {
                              if (value != null)
                                setState(() {
                                  authenticationViewModel.userInfo.password =
                                      value.trim();
                                });
                              this.getProjects(
                                  authenticationViewModel.userInfo.userID);
                            },
                            onClick: () {},
                          ),
                          buildSizedBox(),
                          AppTextFieldCustom(
                            height: textFieldHeight,
                            hintText:
                                TranslationBase.of(context).selectYourProject,
                            hasBorder: true,
                            controller: projectIdController,
                            isTextFieldHasSuffix: true,
                            enabled: false,
                            onClick: projectsList.isEmpty== null ? null:() {
                              Helpers.showCupertinoPicker(
                                  context,
                                  projectsList,
                                  'facilityName',
                                  onSelectProject,
                                  authenticationViewModel);
                            },
                          ),
                          buildSizedBox(),
                        ]),
                  ),
                  SizedBox(
                    height: 40,
                  ),
                ],
              )),
        ),
      ),
      bottomSheet: Container(
// color: Colors.green,
        height: SizeConfig.heightMultiplier * 10,
        width: double.infinity,
        child: Center(
          child: FractionallySizedBox(
            widthFactor: 0.9,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                AppButton(
                  height: SizeConfig.heightMultiplier *
                      (SizeConfig.isHeightVeryShort ? 8 : 6),
                  hPadding: 1,
                  title: TranslationBase.of(context).login,
                  color: Color(0xFFD02127),
                  fontWeight: FontWeight.w700,
                  disabled: authenticationViewModel.userInfo.userID == null ||
                      authenticationViewModel.userInfo.password == null,
                  onPressed: () {
                    login(context);
                  },
                ),

              ],
            ),
          ),
        ),
      ),
    );
  }

  SizedBox buildSizedBox() {
    return SizedBox(
      height: SizeConfig.heightMultiplier * 2,
    );
  }

  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);
        Helpers.showErrorToast(authenticationViewModel.error);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        authenticationViewModel.setUnverified(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(() {
            authenticationViewModel.userInfo.projectID =
                projectsList[0].facilityId;
            projectIdController.text = projectsList[0].facilityName!;
          });
        }
      }
    }
  }
}
