import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/geofencing/requests/GeoZonesRequestModel.dart';
import 'package:hmg_patient_app/core/service/AuthenticatedUserObject.dart';
import 'package:hmg_patient_app/core/service/geofencing/GeofencingServices.dart';
import 'package:hmg_patient_app/core/viewModels/appointment_rate_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/pharmacy_module_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/models/Authentication/check_activation_code_response.dart';
import 'package:hmg_patient_app/models/Authentication/check_paitent_authentication_req.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_info_response_model.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_admission_request_info_response_model.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/pages/login/confirm-login.dart';
import 'package:hmg_patient_app/pages/login/login-type.dart';
import 'package:hmg_patient_app/pages/login/register_new.dart';
import 'package:hmg_patient_app/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:hmg_patient_app/services/authentication/auth_provider.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/services/family_files/family_files_provider.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/habib_logo_widget.dart';
import 'package:hmg_patient_app/widgets/mobile-no/mobile_no.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';

class Login extends StatefulWidget {
  @override
  _Login createState() => _Login();
}

class _Login extends State<Login> {
  final util = Utils();
  final nationalIDorFile = TextEditingController();
  final mobileNumberController = TextEditingController();
  int loginType = LoginType.loginType;
  String? mobileNo;
  String countryCode = '966';
  bool isButtonDisabled = true;
  final authService = AuthProvider();
  var sharedPref = AppSharedPreferences();
  bool isLoading = false;
  AppointmentRateViewModel appointmentRateViewModel =
      locator<AppointmentRateViewModel>();
  PharmacyModuleViewModel pharmacyModuleViewModel =
      locator<PharmacyModuleViewModel>();

  AuthenticatedUserObject authenticatedUserObject =
      locator<AuthenticatedUserObject>();

  late ProjectViewModel projectViewModel;
  late ToDoCountProviderModel toDoProvider;

  var familyFileProvider = FamilyFilesProvider();

  @override
  void initState() {
//    getDeviceToken();
    super.initState();

    // if (BASE_URL.contains("uat.")) {
    //   nationalIDorFile.text = "2001273";
    //   mobileNumberController.text = mobileNo = "0555416043";
    // }
    getRegisterData();
    /* else {
      nationalIDorFile.text = "3376044";
      mobileNumberController.text = mobileNo = "0555416575";
    }*/
  }

  getDeviceToken() async {
    setState(() async {
      nationalIDorFile.text = await sharedPref.getString(PUSH_TOKEN);
    });
  }

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

    return Scaffold(
      backgroundColor: Color(0xfff8f8f8),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          color: Color(0xff2B353E),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Padding(
        padding: EdgeInsets.only(bottom: 20, left: 21, right: 21),
        child: Column(children: [
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              physics: BouncingScrollPhysics(),
              children: [
                SizedBox(height: 12),
                HabibLogoWidget(),
                SizedBox(height: 50),
                Text(
                  loginType == 1
                      ? TranslationBase.of(context).enterNationalId
                      : TranslationBase.of(context).enterFile,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xff2B353E),
                    letterSpacing: -0.64,
                    height: 23 / 16,
                  ),
                ),
                SizedBox(height: 20),
                PhoneNumberSelectorWidget(
                  onNumberChange: (value) => {mobileNo = value, validateForm()},
                  onCountryChange: (value) => countryCode = value,
                  mobileNo: this.mobileNo,
                ),
                SizedBox(height: 12),
                Directionality(
                  textDirection: TextDirection.ltr,
                  child: inputWidget(
                    loginType == 1
                        ? TranslationBase.of(context).nationalIdNumber
                        : TranslationBase.of(context).medicalFileNumber,
                    "Xxxxxxxxx",
                    nationalIDorFile,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 12,
          ),
          DefaultButton(
            TranslationBase.of(context).login,
            () {
              if (isButtonDisabled) {
                AppToast.showErrorToast(message: TranslationBase.of(context).incorrectNationalId, localContext: context);
              } else {
                this.startLogin();
              }
            },
            disabledColor: Color(0xff575757),
          ),
        ]),
      ),
    );
  }

  Widget inputWidget(
      String _labelText, String _hintText, TextEditingController _controller,
      {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.number,
                    controller: _controller,
                    onChanged: (value) => {validateForm()},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

  startLogin() {
    if (isButtonDisabled == false) {
      checkUserAuthentication();
    }
  }

  void validateForm() {
    if (util.validateIDBox(nationalIDorFile.text, loginType) == true &&
        (countryCode == "971" ? true : util.isSAUDIIDValid(nationalIDorFile.text, loginType) == true)) {
      setState(() {
        isButtonDisabled = false;
      });
    } else {
      setState(() {
        isButtonDisabled = true;
      });
    }
  }

  checkUserAuthentication() {
    // showLoader(true);
    var request = CheckPatientAuthenticationReq();
    request.isRegister = false;
    request.patientMobileNumber = int.parse(mobileNo!);
    request.zipCode = countryCode;
    request.searchType = this.loginType;
    request.deviceTypeID = this.loginType;
    if (this.loginType == 1) {
      request.patientIdentificationID = this.nationalIDorFile.text;
      request.patientID = 0;
    } else {
      request.patientIdentificationID = '';
      request.patientID = int.parse(nationalIDorFile.text);
    }
    sharedPref.setObject(REGISTER_DATA_FOR_REGISTER, request);
    GifLoaderDialogUtils.showMyDialog(context);
    authService.checkPatientAuthentication(request).then((value) {
      // if (value['UserAccountIsActivated']) {
      if (value['isSMSSent']) {
        sharedPref.setString(LOGIN_TOKEN_ID, value['LogInTokenID']);
        sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, request);
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.of(context).push(FadePage(page: ConfirmLogin()));
      } else {
        if (value['IsAuthenticated']) {
          this.checkActivationCode();
        }
      }
      // } else {
      //   ConfirmDialog activationDialog = new ConfirmDialog(
      //       context: context,
      //       confirmMessage: TranslationBase.of(context).accountDeactivatedMsg,
      //       okText: TranslationBase.of(context).yes,
      //       cancelText: TranslationBase.of(context).no,
      //       okFunction: () => {ConfirmDialog.closeAlertDialog(context), this.activatePatientFile()},
      //       cancelFunction: () => {});
      //   GifLoaderDialogUtils.hideDialog(context);
      //   activationDialog.showAlertDialog(context);
      // }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      ConfirmDialog dialog = new ConfirmDialog(
          context: context,
          confirmMessage: err,
          okText: TranslationBase.of(context).confirm,
          cancelText: TranslationBase.of(context).cancel_nocaps,
          okFunction: () => {
                ConfirmDialog.closeAlertDialog(context),
                Navigator.of(context).push(FadePage(page: RegisterNew())),
              },
          cancelFunction: () => {});
      dialog.showAlertDialog(context);
      projectViewModel.analytics.loginRegistration
          .login_fail(error: err.toString());
    });
  }

  activatePatientFile() {
    GifLoaderDialogUtils.showMyDialog(context);
    Map<String, dynamic> request = {};
    request["IsActive"] = true;
    if (this.loginType == 1) {
      request['PatientIdentificationID'] = int.parse(nationalIDorFile.text);
    } else {
      request['PatientID'] = int.parse(nationalIDorFile.text);
    }
    request["PatientMobileNumber"] = mobileNo;
    authService.deactivateAccount(request, true).then((result) {
      GifLoaderDialogUtils.hideDialog(context);
      checkUserAuthentication();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
    });
  }

  checkActivationCode({code}) async {
    Map<String, dynamic> request = {};
    if (code == null) request['PatientMobileNumber'] = int.parse(mobileNo!);
    request['ZipCode'] = countryCode;
    request['SearchType'] = loginType;
    request['LoginType'] = loginType;
    if (this.loginType == 1) {
      request['PatientIdentificationID'] = this.nationalIDorFile.text;
      request['PatientID'] = 0;
    } else {
      request['PatientIdentificationID'] = '';
      request['PatientID'] = int.parse(nationalIDorFile.text);
    }
    this.authService.checkActivationCode(request, code).then((result) async {
      sharedPref.remove(FAMILY_FILE);
       // registerGeoZones();
      projectViewModel.setPrivilege(privilegeList: result);
      result = CheckActivationCode.fromJson(result);
      result.list.isFamily = false;
      await this.sharedPref.setString(BLOOD_TYPE,
          result.patientBloodType != null ? result.patientBloodType : "");
      await this.sharedPref.setObject(USER_PROFILE, result.list);
      await this.sharedPref.setObject(MAIN_USER, result.list);
      await this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
      await this.sharedPref.setString(TOKEN, result.authenticationTokenID);
      await authenticatedUserObject.getUser(getUser: true);
      authenticatedUserObject.isLogin = true;
      appointmentRateViewModel.isLogin = true;
      projectViewModel.isLogin = true;
      authenticatedUserObject.user = result.list;
      projectViewModel.user = authenticatedUserObject.user;

      // GifLoaderDialogUtils.hideDialog(context);
      //
      // getToDoCount();
      //
      // Navigator.pushAndRemoveUntil(
      //     context,
      //     FadePage(
      //       page: LandingPage(),
      //     ),
      //         (r) => false);
      getToDoCount();
      checkIfIsInPatient();
      appointmentRateViewModel
          .getIsLastAppointmentRatedList(projectViewModel.isArabic ? 1 : 2)
          .then((value) => {
                GifLoaderDialogUtils.hideDialog(context),
                if (appointmentRateViewModel.isHaveAppointmentNotRate)
                  {
                    Navigator.pushAndRemoveUntil(
                        context,
                        FadePage(
                          page: RateAppointmentDoctor(),
                        ),
                        (r) => false)
                  }
                else
                  {
                    Navigator.pushAndRemoveUntil(
                        context,
                        FadePage(
                          page: LandingPage(),
                        ),
                        (r) => false)
                  }
              })
          .catchError((err) {
        print(err);
        GifLoaderDialogUtils.hideDialog(context);
      });
    });
  }

  getToDoCount() {
    toDoProvider.setState(0, 0, true, toDoProvider.notificationsCount);
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      //print(res['AppointmentActiveNumber']);
      if (res['MessageStatus'] == 1) {
        // toDoProvider.setState(res['AppointmentActiveNumber'], true, toDoProvider.notificationsCount);
        toDoProvider.setState(res['AppointmentActiveNumber'], res['AncillaryOrderListCount'], true, toDoProvider.notificationsCount);

      } else {}
    }).catchError((err) {
      print(err);
    });
  }

  checkIfIsInPatient() async {
    bool isAdmitted = false;
    bool hasAdmissionRequest = false;
    GetAdmissionInfoResponseModel getAdmissionInfoResponseModel;
    GetAdmissionRequestInfoResponseModel getAdmissionRequestInfoResponseModel;
    ClinicListService? service = new ClinicListService();
    dynamic res = await service.checkIfInPatientAPI(context);
    if (res != null) {
      if (res['MessageStatus'] == 1) {
        isAdmitted = res['isAdmitted'];
        hasAdmissionRequest = res['hasAdmissionRequests'];
        print("IS ADMITTED: $isAdmitted");
        print("Has Admission Request: $hasAdmissionRequest");
        if (isAdmitted) {
          if (res['PatientAdmittedInformation'].length != 0) {
            getAdmissionInfoResponseModel =
                GetAdmissionInfoResponseModel.fromJson(
                    res['PatientAdmittedInformation'][0]);
            projectViewModel.setInPatientProjectID(
                res['PatientAdmittedInformation'][0]['ProjectID']);
            projectViewModel
                .setInPatientAdmissionInfo(getAdmissionInfoResponseModel);
            projectViewModel.setIsPatientAdmitted(true);
          }
        }
        if (hasAdmissionRequest) {
          if (res['MedicalInstruction'].length != 0) {
            getAdmissionRequestInfoResponseModel =
                GetAdmissionRequestInfoResponseModel.fromJson(
                    res['MedicalInstruction'][0]);
            projectViewModel.setInPatientProjectID(
                res['MedicalInstruction'][0]['projectId']);
            projectViewModel.setInPatientAdmissionRequest(
                getAdmissionRequestInfoResponseModel);
            projectViewModel.setPatientHasAdmissionRequest(true);
          }
        }
      }
    }
  }

  void registerGeoZones() async {
    await locator<GeofencingServices>().getAllGeoZones(GeoZonesRequestModel());
    projectViewModel.platformBridge().registerHmgGeofences();
  }

  getRegisterData() async {
    var registerData = await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN);
    await sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);

    if (registerData != null) {
      setState(() {
        this.nationalIDorFile.text =
            registerData['PatientIdentificationID'].toString();
        this.isButtonDisabled = false;
        this.loginType = 1;
        this.mobileNo = registerData['PatientMobileNumber'].toString();
      });
    }

    // var voipToken = await sharedPref.getString("VOIPToken");
    // setState(() {
    //   nationalIDorFile.text = voipToken;
    // });
  }
}
