import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart' as checkActivation;
import 'package:diplomaticquarterapp/models/Authentication/check_paitent_authentication_req.dart';
import 'package:diplomaticquarterapp/models/Authentication/register_info_response.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hijri/hijri_calendar.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class RegisterInfo extends StatefulWidget {
  final Function changePageViewIndex;
  final int page;

  const RegisterInfo({Key key, this.changePageViewIndex, this.page = 1}) : super(key: key);

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

class _RegisterInfo extends State<RegisterInfo> {
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();
  RegisterInfoResponse registerInfo;
  bool isLoading;
  int page;
  final List<Location> locationList = [
    new Location(name: 'KSA', value: '1'),
    new Location(name: 'Dubai', value: '2'),
  ];
  String language = '1';
  var registerd_data;
  final List<Language> languageList = [
    new Language(name: 'English', value: '2'),
    new Language(name: 'Arabic', value: '1'),
  ];
  String email = '';

  ToDoCountProviderModel toDoProvider;
  String location = '1';
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

  ProjectViewModel projectViewModel;

  AppointmentRateViewModel appointmentRateViewModel = locator<AppointmentRateViewModel>();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getRegisterInfo();
    });
    setState(() {
      page = widget.page;
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowAppBar: false,
        isShowDecPage: false,
        body: SingleChildScrollView(
          padding: EdgeInsets.all(30),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
            Row(
              children: [
                Expanded(
                  child: AppText(
                    TranslationBase.of(context).personalInfo,
                    fontSize: 16,
                    textAlign: TextAlign.left,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Expanded(child: SizedBox())
              ],
            ),
            SizedBox(height: 20),
            registerInfo != null && page == 1
                ? Column(
                    children: [
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).identificationNumber, registerInfo.idNumber, TranslationBase.of(context).firstName,
                          registerInfo.firstNameEn == '-' ? registerInfo.firstNameAr : registerInfo.firstNameEn),
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).middleName, registerInfo.secondNameEn == '-' ? registerInfo.secondNameEn : registerInfo.secondNameEn,
                          TranslationBase.of(context).lastName, registerInfo.lastNameEn == '-' ? registerInfo.lastNameEn : registerInfo.lastNameEn),
                      SizedBox(height: 20),
                      getnameField(
                          TranslationBase.of(context).gender,
                          registerInfo.maritalStatusCode == 'U'
                              ? 'Unknown'
                              : registerInfo.maritalStatusCode == 'M'
                                  ? 'Male'
                                  : 'Female',
                          TranslationBase.of(context).maritalStatus,
                          registerInfo.maritalStatus),
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).nationality, registerInfo.nationality, TranslationBase.of(context).mobileNumber, registerd_data.patientMobileNumber.toString()),
                      SizedBox(height: 20),
                      getnameField(TranslationBase.of(context).dateOfBirth, registerInfo.dateOfBirth, "", ""),
                      SizedBox(height: 20),
                    ],
                  )
                : registerInfo != null && widget.page == 2
                    ? Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                              width: double.infinity,
                              decoration: containerRadius(Colors.white, 12),
                              padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 25),
                              child: Row(children: [
                                Flexible(
                                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                  Text(
                                    TranslationBase.of(context).prefferedLanguage,
                                    style: TextStyle(
                                      fontSize: 11,
                                      letterSpacing: -0.44,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  Container(
                                      height: 18,
                                      child: DropdownButtonHideUnderline(
                                          child: DropdownButton(
                                              isExpanded: true,
                                              value: language,
                                              hint: Text(TranslationBase.of(context).prefferedLanguage),
                                              iconSize: 40,
                                              elevation: 16,
                                              onChanged: (value) => {
                                                    setState(() {
                                                      language = value;
                                                    })
                                                  },
                                              items: languageList.map<DropdownMenuItem<String>>((Language value) {
                                                return DropdownMenuItem<String>(
                                                  value: value.value,
                                                  child: Text(value.name),
                                                );
                                              }).toList())))
                                ]))
                              ])),
                          SizedBox(
                            height: 20,
                          ),
                          Container(
                              width: double.infinity,
                              decoration: containerRadius(Colors.white, 12),
                              padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 25),
                              child: Row(children: [
                                Flexible(
                                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                  Text(
                                    TranslationBase.of(context).selectLocation,
                                    style: TextStyle(
                                      fontSize: 11,
                                      letterSpacing: -0.44,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  Container(
                                      height: 18,
                                      child: DropdownButtonHideUnderline(
                                          child: DropdownButton(
                                              isExpanded: true,
                                              value: location,
                                              hint: Text(TranslationBase.of(context).selectLocation),
                                              iconSize: 40,
                                              elevation: 16,
                                              onChanged: (value) => {
                                                    setState(() {
                                                      location = value;
                                                    })
                                                  },
                                              items: locationList.map<DropdownMenuItem<String>>((Location value) {
                                                return DropdownMenuItem<String>(
                                                  value: value.value,
                                                  child: Text(
                                                    value.name,
                                                  ),
                                                );
                                              }).toList())))
                                ]))
                              ])),
                          SizedBox(
                            height: 20,
                          ),
                          Container(
                              width: double.infinity,
                              decoration: containerRadius(Colors.white, 12),
                              padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 12),
                              margin: EdgeInsets.only(bottom: 0),
                              child: Row(children: [
                                Flexible(
                                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                                  Text(
                                    TranslationBase.of(context).email,
                                    style: TextStyle(
                                      fontSize: 11,
                                      letterSpacing: -0.44,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  Container(
                                      child: TextField(
                                    onChanged: (value) {
                                      setState(() {
                                        email = value;
                                      });
                                    },
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                    decoration: InputDecoration(
                                      isDense: true,
                                      hintStyle: TextStyle(
                                        fontSize: 14,
                                        height: 21 / 14,
                                        fontWeight: FontWeight.w400,
                                        color: Color(0xff575757),
                                        letterSpacing: -0.56,
                                      ),
                                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                                      contentPadding: EdgeInsets.zero,
                                      border: InputBorder.none,
                                      focusedBorder: InputBorder.none,
                                      enabledBorder: InputBorder.none,
                                    ),
                                  ))
                                ]))
                              ])),
                        ],
                      )
                    : SizedBox(),
          ]),
        ),
        bottomSheet: Container(
            width: double.maxFinite,
            height: 80.0,
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                      padding: EdgeInsets.all(10), child: DefaultButton(TranslationBase.of(context).cancel, () {
                        Navigator.of(context).pop();
                        locator<GAnalytics>().loginRegistration.registration_cancel(step: page == 1 ? 'personal info' : 'other details');
                      }, textColor: Colors.white, color: Color(0xffD02127))),
                ),
                Expanded(
                  child: Padding(
                      padding: EdgeInsets.all(10),
                      child: DefaultButton(
                          page == 1 ? TranslationBase.of(context).next : TranslationBase.of(context).register,
                              (){
                            nextPage();
                            page == 1
                                ? locator<GAnalytics>().loginRegistration.registration_personal_info()
                                : locator<GAnalytics>().loginRegistration.registration_patient_info();

                          },
                          textColor: Colors.white, color: isValid() == true && page == 2 || page == 1 ? Color(0xff359846) : Colors.grey)
                  ),
                ),
              ],
            )));
  }

  nextPage() {
    if (page == 1) {
      setState(() {
        widget.changePageViewIndex(2);
      });
    } else {
      registerNow();
    }
  }

  registerNow() {
    dynamic request = getTempUserRequest();
    GifLoaderDialogUtils.showMyDialog(context);
    dynamic res;
    this
        .authService
        .registerUser(request)
        .then((result) => {
              GifLoaderDialogUtils.hideDialog(context),
              if (result is String)
                {
                  new ConfirmDialog(
                      context: context,
                      confirmMessage: result,
                      okText: TranslationBase.of(context).ok,
                      cancelText: TranslationBase.of(context).cancel_nocaps,
                      okFunction: () => {ConfirmDialog.closeAlertDialog(context)},
                      cancelFunction: () => {ConfirmDialog.closeAlertDialog(context)}).showAlertDialog(context)
                }
              else
                {
                  res = result,
                  result = checkActivation.CheckActivationCode.fromJson(result),
                  // result.list.isFamily = false,
                  // sharedPref.setObject(USER_PROFILE, result.list),
                  // this.sharedPref.setObject(MAIN_USER, result.list),
                  // sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                  // sharedPref.setString(TOKEN, result.authenticationTokenID),
                  // this.setUser(result),
                  sharedPref.remove(FAMILY_FILE),
                  result.list.isFamily = false,

                  sharedPref.setString(BLOOD_TYPE, result.patientBloodType),
                  authenticatedUserObject.user = result.list,
                  projectViewModel.setPrivilege(privilegeList: res),
                  sharedPref.setObject(MAIN_USER, result.list),
                  sharedPref.setObject(USER_PROFILE, result.list),

                  sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID),
                  sharedPref.setString(TOKEN, result.authenticationTokenID),
                  AppToast.showSuccessToast(message: TranslationBase.of(context).successRegister),
                  checkIfUserAgreedBefore(result),
                }
            })
        .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)},
          cancelFunction: () => {ConfirmDialog.closeAlertDialog(context)});
      dialog.showAlertDialog(context);
    });
  }

  setUser(result) async {
    await authenticatedUserObject.getUser(getUser: true);
    authenticatedUserObject.isLogin = true;
    appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    authenticatedUserObject.user = result.list;
    Navigator.of(context).pushNamed(HOME);
  }

  getRegisterInfo() async {
    var data = RegisterInfoResponse.fromJson(await sharedPref.getObject(NHIC_DATA));
    if (await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN) != null) {
      var data2 = CheckPatientAuthenticationReq.fromJson(await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN));

      setState(() {
        this.registerInfo = data;

        this.registerd_data = data2;
      });
    }
  }

  getTempUserRequest() {
    DateFormat dateFormat = DateFormat("mm/dd/yyyy");
    print(dateFormat.parse(registerInfo.dateOfBirth));
    var hDate = new HijriCalendar.fromDate(dateFormat.parse(registerInfo.dateOfBirth));
    var date = hDate.toString();
    return {
      "Patientobject": {
        "TempValue": true,
        "PatientIdentificationType": registerInfo.idNumber.substring(0, 1) == "1" ? 1 : 2,
        "PatientIdentificationNo": registerInfo.idNumber,
        "MobileNumber": registerd_data.patientMobileNumber,
        "PatientOutSA": registerd_data.zipCode == '966' ? 0 : 1,
        "FirstNameN": registerInfo.firstNameAr,
        "FirstName": registerInfo.firstNameEn,
        "MiddleNameN": registerInfo.secondNameAr,
        "MiddleName": registerInfo.secondNameEn,
        "LastNameN": registerInfo.lastNameAr,
        "LastName": registerInfo.lastNameEn,
        "StrDateofBirth": registerInfo.dateOfBirth,
        "DateofBirth": DateUtil.convertISODateToJsonDate(registerInfo.dateOfBirth.replaceAll('/', '-')),
        "Gender": registerInfo.gender == 'M' ? 1 : 2,
        "NationalityID": registerInfo.nationalityCode,
        "eHealthIDField": registerInfo.healthId,
        "DateofBirthN": date,
        "EmailAddress": email,
        "SourceType": location,
        "PreferredLanguage": registerd_data.languageID.toString(),
        "Marital": registerInfo.maritalStatusCode == 'U'
            ? '0'
            : registerInfo.maritalStatusCode == 'M'
                ? '1'
                : '2',
      },
      "PatientIdentificationID": registerInfo.idNumber,
      "PatientMobileNumber": registerd_data.patientMobileNumber.toString()[0] == '0' ? registerd_data.patientMobileNumber : '0' + registerd_data.patientMobileNumber.toString(),
    };
  }

  bool isValid() {
    if (location != null && language != null && Utils.validEmail(email) == true) {
      return true;
    } else {
      return false;
    }
  }

  Widget getnameField(name1, value1, name2, value2) {
    return Row(
      children: [
        Expanded(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              name1,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                letterSpacing: -0.44,
              ),
            ),
            Text(
              value1,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                letterSpacing: -0.44,
              ),
            ),
          ],
        )),
        Expanded(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              name2,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                letterSpacing: -0.44,
              ),
            ),
            Text(
              value2,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w600,
                letterSpacing: -0.44,
              ),
            ),
          ],
        ))
      ],
    );
  }

  checkIfUserAgreedBefore(checkActivation.CheckActivationCode result) {
    if (result.isNeedUserAgreement == true) {
      //TODO need to implement agreement page here
      insertIMEI();
    } else {
      insertIMEI();
    }
  }

  insertIMEI() async {
    var selectedOption = await sharedPref.getInt(LAST_LOGIN);
    authService.insertDeviceImei(selectedOption).then((value) => {goToHome()}).catchError((err) {
      print(err);
    });
  }

  goToHome() async {
    authenticatedUserObject.isLogin = true;
    appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    projectViewModel.user = authenticatedUserObject.user;
    await authenticatedUserObject.getUser(getUser: true);
    appointmentRateViewModel
        .getIsLastAppointmentRatedList()
        .then((value) => {
              getToDoCount(),
              GifLoaderDialogUtils.hideDialog(AppGlobal.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);
    });
    // SMSOTP.showLoadingDialog(context, false),
  }

  getToDoCount() {
    toDoProvider.setState(0, true, "0");
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      if (res['MessageStatus'] == 1) {
        toDoProvider.setState(res['AppointmentActiveNumber'], true, "0");
      } else {}
    }).catchError((err) {
      print(err);
    });
  }
}

class Language {
  final String name;
  final String value;

  Language({this.name, this.value});
}

class Location {
  final String name;
  final String value;

  Location({this.name, this.value});
}
