import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_paitent_authentication_req.dart';
import 'package:diplomaticquarterapp/models/Authentication/register_info_response.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart'
    as checkActivation;
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.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/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/input/text_field.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hijri/hijri_calendar.dart';
import 'package:intl/intl.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:provider/provider.dart';

class RegisterInfo extends StatefulWidget {
  @override
  _RegisterInfo createState() => _RegisterInfo();
}

class _RegisterInfo extends State<RegisterInfo> {
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();
  RegisterInfoResponse registerInfo;
  bool isLoading;
  int page = 1;
  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 = '';

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

  ProjectViewModel projectViewModel;

  AppointmentRateViewModel appointmentRateViewModel =
      locator<AppointmentRateViewModel>();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getRegisterInfo();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowAppBar: true,
        isShowDecPage: false,
        body: SingleChildScrollView(
          padding: EdgeInsets.all(20),
          child: Column(children: <Widget>[
            AppText(
              TranslationBase.of(context).patientInfo,
              fontSize: SizeConfig.textMultiplier * 3,
              textAlign: TextAlign.left,
            ),
            registerInfo != null && page == 1
                ? Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      AppText(TranslationBase.of(context).nationalID),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.idNumber,
                            prefixIcon: Icon(Icons.chrome_reader_mode,
                                color: Colors.red),
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).firstName),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.firstNameEn == '-'
                                ? registerInfo.firstNameAr
                                : registerInfo.firstNameEn,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).middleName),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.secondNameEn == '-'
                                ? registerInfo.secondNameAr
                                : registerInfo.secondNameEn,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).lastName),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.lastNameEn == '-'
                                ? registerInfo.lastNameAr
                                : registerInfo.lastNameEn,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).gender),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.maritalStatusCode == 'U'
                                ? 'Unknown'
                                : registerInfo.maritalStatusCode == 'M'
                                    ? 'Male'
                                    : 'Female',
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).maritalStatus),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.maritalStatus,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).nationality),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.nationalityCode,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).mobileNumber),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText:
                                registerd_data.patientMobileNumber.toString(),
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                      AppText(TranslationBase.of(context).dob),
                      Container(
                          margin: EdgeInsets.only(bottom: 10),
                          child: TextFields(
                            hintText: registerInfo.dateOfBirth,
                            padding: EdgeInsets.only(
                                top: 20, bottom: 20, left: 10, right: 10),
                            readOnly: true,
                          )),
                    ],
                  )
                : registerInfo != null && page == 2
                    ? Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          AppText(TranslationBase.of(context).language,
                              textAlign: TextAlign.start),
                          Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(color: Colors.grey),
                                  borderRadius: BorderRadius.circular(10)),
                              child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                      isExpanded: true,
                                      value: language,
                                      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()))),
                          AppText(TranslationBase.of(context).location),
                          Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(color: Colors.grey),
                                  borderRadius: BorderRadius.circular(10)),
                              child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                      isExpanded: true,
                                      value: location,
                                      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()))),
                          AppText(TranslationBase.of(context).email),
                          Container(
                              margin: EdgeInsets.only(bottom: 10),
                              child: TextFields(
                                onChanged: (value) => {
                                  setState(() {
                                    email = value;
                                  })
                                },
                                padding: EdgeInsets.only(
                                    top: 20, bottom: 20, left: 10, right: 10),
                              )),
                        ],
                      )
                    : SizedBox(),
            Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                        child: DefaultButton(
                      page == 1
                          ? TranslationBase.of(context).next
                          : TranslationBase.of(context).register,
                      () => {nextPage()},
                      textColor: Colors.white,
                      color: this.isValid() == false && page == 2
                          ? Colors.grey
                          : Colors.black,
                    ))
                  ],
                ),
              ],
            )
          ]),
        ));
  }

  nextPage() {
    if (page == 1) {
      setState(() {
        page++;
      });
    } else {
      registerNow();
    }
  }

  registerNow() {
    dynamic request = getTempUserRequest();
    GifLoaderDialogUtils.showMyDialog(context);
    this
        .authService
        .registerUser(request)
        .then((result) => {
              GifLoaderDialogUtils.hideDialog(context),
              // userData = result.list;
              //AuthenticatedUser.fromJson(result['List'][0]),
              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
                {
                  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),
                }
            })
        .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": 1,
        "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,
    };
  }

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

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});
}
