import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.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/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/habib_logo_widget.dart';
import 'package:diplomaticquarterapp/widgets/mobile-no/mobile_no.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/otp/sms-popup.dart';
import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ForgotPassword extends StatefulWidget {
  @override
  _ForgotPassword createState() => _ForgotPassword();
}

class _ForgotPassword extends State<ForgotPassword> {
  String selectedType = 'Saudi Arabia';
  String countryCode = '966';
  final TextEditingController nationalIDorFile = null;
  String mobileNo = "";
  var con;

  @override
  Widget build(BuildContext context) {
    con = 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(
                  TranslationBase.of(context).forgotDesc,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64, height: 23 / 16),
                ),
                SizedBox(height: 20),
                PhoneNumberSelectorWidget(onNumberChange: (value) {
                  setState(() {
                    mobileNo = value;
                  });
                }, onCountryChange: (value) {
                  setState(() {
                    countryCode = value;
                  });
                }),
              ],
            ),
          ),
          SizedBox(
            height: 43,
            width: double.infinity,
            child: FlatButton(
              onPressed: () {
                locator<GAnalytics>().loginRegistration.recover_file_number();
                sendPatientIDBySMS();
              },
              child: Text(
                TranslationBase.of(context).submit,
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.white, letterSpacing: -0.48),
              ),
              //     color: Color(0xffD02127),
              color: (mobileNo.length >= 9) == true ? Color(0xffD02127) : Color(0xff575757),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
            ),
          ),
        ]),
      ),
    );

    return AppScaffold(
        appBarTitle: TranslationBase.of(context).forgotFileNoTitle,
        isShowAppBar: true,
        isShowDecPage: false,
        body: SingleChildScrollView(
            child: Container(
          padding: EdgeInsets.only(top: 10, left: 20, right: 20),
          height: SizeConfig.realScreenHeight * .8,
          width: SizeConfig.realScreenWidth,
          child: Column(children: <Widget>[
            Expanded(
                flex: 1,
                child: AppText(
                  TranslationBase.of(context).forgotDesc,
                  fontSize: SizeConfig.textMultiplier * 3,
                  textAlign: TextAlign.start,
                  marginTop: 10.0,
                )),
            Expanded(
              flex: 2,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[],
                  ),
                  MobileNo(onNumberChange: (value) {
                    setState(() {
                      mobileNo = value;
                    });
                  }, onCountryChange: (value) {
                    setState(() {
                      countryCode = value;
                    });
                  }),
                ],
              ),
            ),
            Expanded(
                flex: 2,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: DefaultButton(
                          TranslationBase.of(context).submit,
                          () {
                            // if (mobileNo.length >= 9 == true)
                            //   sendPatientIDBySMS();
                            if (mobileNo.length >= 9) sendPatientIDBySMS();
//                            print(mobileNo.text);
                          },
                          color: mobileNo.length >= 9 == true ? Colors.grey[900] : Colors.grey,
                          textColor: Colors.white,
                        )),
                      ],
                    ),
                  ],
                ))
          ]),
        )));
  }

  sendPatientIDBySMS() {
    GifLoaderDialogUtils.showMyDialog(context);
    final authService = new AuthProvider();
    authService.sendPatientIDSMS(mobileNo, countryCode, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        this.startSMSService(mobileNo, res['LogInTokenID']);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  startSMSService(mobile, token) {
    new SMSOTP(
      context,
      1,
      mobile,
      (value) => {this.checkActivationCode(value, token, int.parse(mobileNo))},
      () => {
        print('Faild..'),
      },
    ).displayDialog(context);
  }

  checkActivationCode(value, token, mobileNo) {
    GifLoaderDialogUtils.showMyDialog(context);
    final authService = new AuthProvider();
    var request = {
      "LogInTokenID": token,
      "PatientOutSA": countryCode == '966' ? 0 : 1,
      "PatientMobileNumber": mobileNo,
      "ZipCode": countryCode,
      "activationCode": value,
      "isRegister": false,
      "IsSilentLogin": false
    };
    authService.forgotPasswordActivation(request, value).then((res) {
      if (res is String) {
        GifLoaderDialogUtils.hideDialog(con);
        Future.delayed(Duration(seconds: 1), () {
          AppToast.showErrorToast(message: res);
        });
      } else {
        GifLoaderDialogUtils.hideDialog(con);
        Navigator.of(context).pop();
        AlertDialogBox(
            context: con,
            confirmMessage: res['ReturnMessage'],
            okText: TranslationBase.of(con).ok,
            okFunction: () {
              AlertDialogBox.closeAlertDialog(con);
              Navigator.of(context).pop();
            }).showAlertDialog(context);
      }
    });
  }
}
