import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_activation_code_response.dart';
import 'package:diplomaticquarterapp/models/Authentication/register_info_response.dart';
import 'package:diplomaticquarterapp/models/Authentication/register_user_requet.dart';
import 'package:diplomaticquarterapp/pages/login/login-type.dart';
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/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/buttons/button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/card/rounded_container.dart';
import 'package:diplomaticquarterapp/widgets/input/text_field.dart';
import 'package:diplomaticquarterapp/widgets/mobile-no/mobile_no.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/progress_indicator/app_circular_progress_Indeicator.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hijri/hijri_calendar.dart';
import 'package:intl/intl.dart';

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

class _RegisterInfo extends State<RegisterInfo> {
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();
  var emailAddress = new TextEditingController();
  RegisterInfoResponse registerInfo;
  bool isLoading;
  int page = 1;
  String selectedLanguage = 'English';
  var registerRequest;

  var selectSourceType = 'KSA';
  @override
  void initState() {
    getRegisterInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowAppBar: true,
        body: SingleChildScrollView(
            child: Container(
          // padding: EdgeInsets.only(top: 10, left: 10, right: 10, bottom: 30),
          height: SizeConfig.realScreenHeight,
          width: SizeConfig.realScreenWidth,
          child: RoundedContainer(
              child: Padding(
                  padding:
                      EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 0),
                  child: Stack(
                    // crossAxisAlignment: CrossAxisAlignment.start,
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                          padding: EdgeInsets.only(bottom: 0),
                          child: AppText(
                            TranslationBase.of(context).patientInfo,
                            fontWeight: FontWeight.bold,
                            // fontSize: SizeConfig.textMultiplier * 2,
                            textAlign: TextAlign.left,
                          )),
                      registerInfo != null && page == 1
                          ? Padding(
                              padding: EdgeInsets.only(top: 20),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  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,
                                        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,
                                        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,
                                        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'
                                                ? AppText(
                                                    TranslationBase.of(context)
                                                        .male)
                                                : AppText(
                                                    TranslationBase.of(context)
                                                        .female),
                                        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).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
                              ? isLoading == true
                                  ? AppCircularProgressIndicator()
                                  : Padding(
                                      padding: EdgeInsets.only(top: 20),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: <Widget>[
                                          AppText(TranslationBase.of(context)
                                              .prefferedLanguage),
                                          Container(
                                              margin: EdgeInsets.only(top: 0),
                                              decoration: BoxDecoration(
                                                  border: Border.all(
                                                      color: Colors.grey,
                                                      width: 1),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          5.0)),
                                              padding: EdgeInsets.all(5),
                                              child:
                                                  DropdownButtonHideUnderline(
                                                      child: DropdownButton(
                                                          focusColor:
                                                              Colors.white,
                                                          dropdownColor:
                                                              Colors.white,
                                                          isExpanded: true,
                                                          value:
                                                              selectedLanguage,
                                                          iconSize: 40,
                                                          elevation: 16,
                                                          onChanged: (String
                                                                  newValue) =>
                                                              {},
                                                          items: <String>[
                                                            TranslationBase.of(
                                                                    context)
                                                                .english,
                                                            TranslationBase.of(
                                                                    context)
                                                                .arabic,
                                                          ].map<
                                                              DropdownMenuItem<
                                                                  String>>((String
                                                              value) {
                                                            return DropdownMenuItem<
                                                                String>(
                                                              value: value,
                                                              child:
                                                                  Text(value),
                                                            );
                                                          }).toList()))),
                                          AppText(TranslationBase.of(context)
                                              .registrLocation),
                                          Container(
                                              margin:
                                                  EdgeInsets.only(bottom: 10),
                                              decoration: BoxDecoration(
                                                  border: Border.all(
                                                      color: Colors.grey,
                                                      width: 1),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          5.0)),
                                              padding: EdgeInsets.all(5),
                                              child:
                                                  DropdownButtonHideUnderline(
                                                      child: DropdownButton(
                                                          focusColor:
                                                              Colors.white,
                                                          dropdownColor:
                                                              Colors.white,
                                                          isExpanded: true,
                                                          value:
                                                              selectSourceType,
                                                          iconSize: 40,
                                                          elevation: 16,
                                                          onChanged: (String
                                                                  newValue) =>
                                                              {},
                                                          items: <String>[
                                                            TranslationBase.of(
                                                                    context)
                                                                .ksa,
                                                            TranslationBase.of(
                                                                    context)
                                                                .dubai,
                                                          ].map<
                                                              DropdownMenuItem<
                                                                  String>>((String
                                                              value) {
                                                            return DropdownMenuItem<
                                                                String>(
                                                              value: value,
                                                              child:
                                                                  Text(value),
                                                            );
                                                          }).toList()))),
                                          AppText(TranslationBase.of(context)
                                              .enterEmail),
                                          Container(
                                              margin:
                                                  EdgeInsets.only(bottom: 10),
                                              child: TextFields(
                                                hintText:
                                                    TranslationBase.of(context)
                                                        .enterEmail,
                                                controller: emailAddress,
                                                padding: EdgeInsets.only(
                                                    top: 20,
                                                    bottom: 20,
                                                    left: 10,
                                                    right: 10),
                                              ))
                                        ],
                                      ))
                              : SizedBox(),
                      // AppText('National ID'),

                      page == 1
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: <Widget>[
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: <Widget>[
                                    Expanded(
                                        child: DefaultButton(
                                      TranslationBase.of(context).next,
                                      () => {nextPage()},
                                      textColor: Colors.white,
                                    ))
                                  ],
                                )
                              ],
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: <Widget>[
                                  Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                      children: <Widget>[
                                        Expanded(
                                            child: DefaultButton(
                                          TranslationBase.of(context).register,
                                          () => {registerNow()},
                                          textColor: Colors.white,
                                        ))
                                      ])
                                ])
                    ],
                  ))),
        )));
  }

  nextPage() {
    setState(() {
      page++;
    });
  }

  registerNow() {
    var patientRequest = Patientobject();
    var request = RegisterUserRequest();
    showLoader(true);
    patientRequest.dateofBirth = DateUtil.convertISODateToJsonDate(
        registerInfo.dateOfBirth.replaceAll('/', '-'));
    patientRequest.emailAddress = emailAddress.text;
    patientRequest.patientIdentificationNo = registerInfo.idNumber;
    patientRequest.patientIdentificationType = 2;
    patientRequest.sourceType = selectSourceType == 'KSA' ? '1' : '2';
    patientRequest.nationalityID = registerInfo.nationalityCode;
    patientRequest.dateofBirthN = HijriCalendar.fromDate(DateFormat('mm-dd-yyy')
            .parse(registerInfo.dateOfBirth.replaceAll('/', '-')))
        .toString();
    patientRequest.firstName = registerInfo.firstNameEn;
    patientRequest.middleName = registerInfo.secondNameEn;
    patientRequest.lastName = registerInfo.lastNameEn;
    patientRequest.gender = registerInfo.gender == 'F' ? 2 : 1;
    patientRequest.mobileNumber = registerRequest['PatientMobileNumber'];
    patientRequest.marital = registerInfo.maritalStatusCode == 'M' ? '1' : '0';
    // patientRequest.projectID = null;
    patientRequest.strDateofBirth = DateFormat('mm-dd-yyy')
        .parse(registerInfo.dateOfBirth.replaceAll('/', '-'))
        .toString(); //DateFormat("MM-dd-yyyy")
    //.parse(registerInfo.dateOfBirth.replaceAll('/', '-'));
    patientRequest.tempValue = true;
    request.logInTokenID = registerRequest['LogInTokenID'];
    request.patientMobileNumber = registerRequest['PatientMobileNumber'];
    request.patientIdentificationID = registerInfo.idNumber;
    request.patientOutSA = registerRequest['PatientOutSA'];
    request.patientobject = patientRequest;
    request.patientobject.preferredLanguage =
        selectedLanguage == 'Arabic' ? '1' : '2';
    authService.registerUser(request).then((value) => {registerd(value)});
  }

  registerd(result) {
    showLoader(false);
    if (result is Map) {
      result = CheckActivationCode.fromJson(result);

      // this.userData =
      //     result.list; //AuthenticatedUser.fromJson(result['List'][0]),
      this.sharedPref.setObject(USER_PROFILE, result.list);
      // this.loginTokenID = result.logInTokenID;
      this.sharedPref.setObject(LOGIN_TOKEN_ID, result.logInTokenID);
      this.sharedPref.setString(TOKEN, result.authenticationTokenID);
      this.checkIfUserAgreedBefore(result);
      // Navigator.of(context).pop(),

    } else {
      // Navigator.of(context).pop(),
      AppToast.showErrorToast(message: result);
    }
  }

  checkIfUserAgreedBefore(result) {
    if (result.isNeedUserAgreement) {
      //move to agreement page.
    } else {
      insertIMEI();
    }
  }

  insertIMEI() {
    authService
        .insertDeviceImei()
        .then((value) => {Navigator.of(context).pushNamed(HOME)});
  }

  getRegisterInfo() async {
    registerInfo =
        RegisterInfoResponse.fromJson(await sharedPref.getObject(NHIC_DATA));
    registerRequest = await sharedPref.getObject(REGISTER_DATA_FOR_LOGIIN);
    setState(() {
      registerInfo = registerInfo;
    });
    print(await sharedPref.getObject(NHIC_DATA));
  }

  showLoader(bool isTrue) {
    setState(() {
      isLoading = isTrue;
    });
  }
}
