import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_user_status_reponse.dart';
import 'package:diplomaticquarterapp/models/Authentication/check_user_status_req.dart';
import 'package:diplomaticquarterapp/models/Authentication/checkpatient_for_registration.dart';
import 'package:diplomaticquarterapp/pages/login/confirm-login.dart';
import 'package:diplomaticquarterapp/pages/login/login-type.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/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/alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.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/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:intl/intl.dart';

class Register extends StatefulWidget {
  @override
  _Register createState() => _Register();
}

class _Register extends State<Register> {
  final nationalIDorFile = TextEditingController();
  final int loginType = LoginType.loginType;
  String mobileNo;
  String countryCode = '966';
  var isHijri;
  final util = Utils();
  DateTime selectedDate;
  String dob;
  bool isButtonDisabled = true;
  final authService = new AuthProvider();
  final sharedPref = new AppSharedPreferences();

  bool isLoading;

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).register,
        isShowAppBar: true,
        isShowDecPage: false,
        body: SingleChildScrollView(
            child: Container(
          padding: EdgeInsets.only(top: 10, left: 20, right: 20, bottom: 30),
          height: SizeConfig.realScreenHeight * .9,
          width: SizeConfig.realScreenWidth,
          child: Column(children: <Widget>[
            Expanded(
                flex: 1,
                child: AppText(
                  TranslationBase.of(context).enterNationalId,
                  fontSize: SizeConfig.textMultiplier * 3,
                  textAlign: TextAlign.left,
                )),
            Expanded(
              flex: 4,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  MobileNo(
                      onNumberChange: (value) =>
                          {mobileNo = value, validateForm()},
                      onCountryChange: (value) => countryCode = value),
                  Container(
                      child: TextFields(
                    controller: nationalIDorFile,
                    onChanged: (value) => validateForm(),
                    keyboardType: TextInputType.number,
                    prefixIcon: Icon(Icons.chrome_reader_mode,
                        color: Color(0xFF40ACC9)),
                    padding: EdgeInsets.only(
                        top: 20, bottom: 20, left: 10, right: 10),
                    hintText: TranslationBase.of(context).nationalID,
                  )),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Row(
                          children: <Widget>[
                            Radio(
                              value: 1,
                              groupValue: isHijri,
                              onChanged: (value) {
                                setState(() {
                                  isHijri = value;
                                });
                                validateForm();
                              },
                            ),
                            Text(TranslationBase.of(context).hijriDate),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Row(
                          children: <Widget>[
                            Radio(
                              value: 0,
                              groupValue: isHijri,
                              onChanged: (value) {
                                setState(() {
                                  isHijri = value;
                                });
                                validateForm();
                              },
                            ),
                            Text(TranslationBase.of(context).gregorianDate),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Container(
                            width: SizeConfig.realScreenWidth * .9,
                            height: 60,
                            child: isHijri == 1
                                ? TextFields(
                                    onChanged: (value) => {dob = value},
                                    hintText: 'DD/MM/YYYY',
                                    prefixIcon: Icon(Icons.date_range),
                                  )
                                : RaisedButton.icon(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(15.0),
                                    ),
                                    color: Colors.white,
                                    onPressed: () => {
                                          if (isHijri != null)
                                            _selectDate(context)
                                        },
                                    icon: Icon(Icons.date_range),
                                    label: Text(selectedDate != null
                                        ? "${selectedDate.toLocal()}"
                                            .split(' ')[0]
                                        : TranslationBase.of(context).dob)))
                      ])
                ],
              ),
            ),
            Expanded(
                flex: 2,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Divider(
                      color: Colors.grey,
                      height: 2,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: DefaultButton(
                                TranslationBase.of(context).registerNow,
                                () => {startRegistration()},
                                textColor: Colors.white,
                                color: isButtonDisabled == true
                                    ? Colors.grey
                                    : Colors.grey[900]))
                      ],
                    ),
                  ],
                ))
          ]),
        )));
  }

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1950, 8),
        lastDate: DateTime.now());
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  startRegistration() {
    if (isButtonDisabled == false) {
      var request = CheckPatientForRegistration();
      request.patientMobileNumber = int.parse(mobileNo);
      request.zipCode = countryCode;
      request.patientOutSA = countryCode == '966' ? 0 : 1;
      // if (this.loginType == 1) {
      request.patientIdentificationID = int.parse(nationalIDorFile.text);
      request.patientID = 0;
      request.isRegister = true;
      // } else {
      //   request.patientIdentificationID = 0;
      //   request.patientID = int.parse(nationalIDorFile.text);
      // }
      this.checkPatientForRegisteration(request);
    }
  }

  checkPatientForRegisteration(request) {
    GifLoaderDialogUtils.showMyDialog(context);
    this
        .authService
        .checkPatientForRegisteration(request)
        .then((response) => {checkUserStatus(response, request)})
        .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: Register())),
              },
          cancelFunction: () => {ConfirmDialog.closeAlertDialog(context)});
      dialog.showAlertDialog(context);
    });
  }

  void validateForm() {
    if (util.validateIDBox(nationalIDorFile.text, loginType) == true &&
        mobileNo.length >= 9 &&
        util.isSAUDIIDValid(nationalIDorFile.text, loginType) == true &&
        isHijri != null) {
      setState(() {
        isButtonDisabled = false;
      });
    } else {
      setState(() {
        isButtonDisabled = true;
      });
    }
  }

  checkUserStatus(response, CheckPatientForRegistration request) async {
    GifLoaderDialogUtils.hideDialog(context);
    if (response is Map) {
      var nRequest = request.toJson();
      nRequest['LogInTokenID'] = response['LogInTokenID'];
      if (response['hasFile'] == true) {
        // AppToast.showErrorToast(message: response['ErrorEndUserMessage']);
        AlertDialogBox(
            context: context,
            confirmMessage: response['ErrorEndUserMessage'],
            okText: TranslationBase.of(context).ok,
            okFunction: () {
              AlertDialogBox.closeAlertDialog(context);
              Navigator.of(context).pop();
            }).showAlertDialog(context);
      } else {
        nRequest['forRegister'] = true;
        nRequest['isRegister'] = true;
        nRequest["PatientIdentificationID"] =
            nRequest["PatientIdentificationID"].toString();
        sharedPref.setObject(REGISTER_DATA_FOR_LOGIIN, nRequest);
        sharedPref.setString(LOGIN_TOKEN_ID, response['LogInTokenID']);
        this.chekUserData(response['LogInTokenID']);
      }
    } else {
      // if (response['ErrorCode'] == '-986') {
      //AppToast.showErrorToast(message: response);
      AlertDialogBox(
          context: context,
          confirmMessage: response,
          okText: TranslationBase.of(context).ok,
          okFunction: () {
            AlertDialogBox.closeAlertDialog(context);
            Navigator.of(context).pop();
          }).showAlertDialog(context);
      //}
    }
  }

  chekUserData(loginToken) {
    //  let m = hijri(this.dateOfBirth).locale('en');
    //     // const dateHijri = m.format('iDD/iMM/iYYYY');
    //     const request = {
    //         PatientIdentificationID: this.id.toString(),
    //         // TokenID: token,
    //         DOB: this.dateOption === '1' ? this.dateOfBirth : moment(this.dateOfBirth).format('DD/MM/YYYY'),
    //         IsHijri: Number(this.dateOption)
    //     }

    final DateFormat dateFormat = DateFormat('dd/MM/yyyy');
    GifLoaderDialogUtils.showMyDialog(context);
    var request = CheckUserStatusRequest();
    request.patientIdentificationID = nationalIDorFile.text;
    request.dOB = isHijri == 1 ? dob : dateFormat.format(selectedDate);
    request.isHijri = isHijri;
    request.patientOutSA = countryCode == '966' ? 0 : 1;
    this.authService.checkUserStatus(request).then((result) => {
          GifLoaderDialogUtils.hideDialog(context),
          if (result is Map)
            {
              result = CheckUserStatusResponse.fromJson(result),
              sharedPref.setObject(NHIC_DATA, result),
              Navigator.of(context).push(FadePage(page: ConfirmLogin())),
            }
          else
            {
              AppToast.showErrorToast(
                  message: result
                      ? result
                      : TranslationBase.of(context).somethingWentWrong)
            }
        });
  }

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