import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientRegistrationViewModel.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

class ActivationPage extends StatefulWidget {
  final PatientRegistrationViewModel? model;
  final Function? changePageViewIndex;

  ActivationPage({this.model, this.changePageViewIndex});

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

class _ActivationPageState extends State<ActivationPage> {
  bool isSendOtp = false;
  final verifyAccountForm = GlobalKey<FormState>();

  TextStyle buildTextStyle() {
    return TextStyle(
      fontSize: SizeConfig.textMultiplier! * 3,
    );
  }

  Map verifyAccountFormValue = {
    'digit1': '',
    'digit2': '',
    'digit3': '',
    'digit4': '',
  };
  final focusD1 = FocusNode();
  final focusD2 = FocusNode();
  final focusD3 = FocusNode();
  final focusD4 = FocusNode();

  TextEditingController digit1 = TextEditingController(text: "");
  TextEditingController digit2 = TextEditingController(text: "");
  TextEditingController digit3 = TextEditingController(text: "");
  TextEditingController digit4 = TextEditingController(text: "");

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
        baseViewModel: widget.model!,
        isShowAppBar: false,
        body: Column(
          children: [
            Visibility(
              //visible: isSendOtp,
              child: !isSendOtp
                  ? Container(
                      width: double.infinity,
                      margin: EdgeInsets.all(16.0),
                      child: SingleChildScrollView(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppText(
                              "Please select how you want to be verified",
                              fontFamily: 'Poppins',
                              fontSize: SizeConfig.textMultiplier! * 2.2,
                              fontWeight: FontWeight.w800,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () async {
                                      await sendActivationCode(1);
                                      setState(() {
                                        isSendOtp = true;
                                      });
                                      //
                                      // await widget.model
                                      //     .sendActivationCodeByOTPNotificationType(
                                      //     otpType: 1);
                                    },
                                    child: Container(
                                      height: MediaQuery.of(context).size.height * 0.233,
                                      margin: EdgeInsets.all(10),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(10),
                                        ),
                                        border: Border.all(color: HexColor('#707070'), width: 0.1),
                                      ),
                                      child: Column(
                                        children: [
                                          Row(
                                            children: [
                                              Padding(
                                                padding: EdgeInsets.symmetric(horizontal: 10),
                                                child: Image.asset(
                                                  "assets/images/verify-sms.png",
                                                  height: MediaQuery.of(context).size.height * 0.15,
                                                  width: MediaQuery.of(context).size.width * 0.15,
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: 20,
                                          ),
                                          Center(
                                            child: AppText(
                                              TranslationBase.of(context).verifySMS,
                                              fontSize: 14,
                                              color: Color(0xFF2E303A),
                                              fontWeight: FontWeight.bold,
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () async {
                                      await sendActivationCode(2);
                                      setState(() {
                                        isSendOtp = true;
                                      });
                                    },
                                    child: Container(
                                      height: MediaQuery.of(context).size.height * 0.233,
                                      margin: EdgeInsets.all(10),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(10),
                                        ),
                                        border: Border.all(color: HexColor('#707070'), width: 0.1),
                                      ),
                                      child: Column(
                                        children: [
                                          Row(
                                            children: [
                                              Padding(
                                                padding: EdgeInsets.symmetric(horizontal: 10.0),
                                                child: Image.asset(
                                                  "assets/images/verify-whtsapp.png",
                                                  height: MediaQuery.of(context).size.height * 0.15,
                                                  width: MediaQuery.of(context).size.width * 0.15,
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(
                                            height: 20,
                                          ),
                                          Center(
                                            child: AppText(
                                              TranslationBase.of(context).verifyWhatsApp,
                                              fontSize: 14,
                                              color: Color(0xFF2E303A),
                                              fontWeight: FontWeight.bold,
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    )
                  : Container(
                      width: double.infinity,
                      margin: EdgeInsets.all(16.0),
                      child: SingleChildScrollView(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            AppText(
                              TranslationBase.of(context).verificationMessage,
                              fontFamily: 'Poppins',
                              fontSize: SizeConfig.textMultiplier! * 2.2,
                              fontWeight: FontWeight.w800,
                            ),
                            Row(
                              children: [
                                Center(
                                    child: SingleChildScrollView(
                                        child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Form(
                                      key: verifyAccountForm,
                                      child: Padding(
                                        padding: EdgeInsets.only(top: 20),
                                        child: Directionality(
                                            textDirection: TextDirection.ltr,
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.start,
                                              children: <Widget>[
                                                Container(
                                                  width: SizeConfig.realScreenWidth! * 0.16,
                                                  margin: EdgeInsets.all(5),
                                                  child: TextFormField(
                                                    textInputAction: TextInputAction.next,
                                                    style: buildTextStyle(),
                                                    autofocus: true,
                                                    maxLength: 1,
                                                    controller: digit1,
                                                    textAlign: TextAlign.center,
                                                    keyboardType: TextInputType.number,
                                                    decoration: buildInputDecoration(context),
                                                    onSaved: (val) {},
                                                    //validator: validateCodeDigit,
                                                    onFieldSubmitted: (_) {
                                                      FocusScope.of(context).requestFocus(focusD2);
                                                    },
                                                    onChanged: (val) {
                                                      if (val.length == 1) {
                                                        FocusScope.of(context).requestFocus(focusD2);
                                                        verifyAccountFormValue['digit1'] = val.trim();
                                                        //checkValue();
                                                      }
                                                    },
                                                  ),
                                                ),
                                                Container(
                                                  width: SizeConfig.realScreenWidth! * 0.16,
                                                  margin: EdgeInsets.all(5),
                                                  child: TextFormField(
                                                    focusNode: focusD2,
                                                    textInputAction: TextInputAction.next,
                                                    maxLength: 1,
                                                    controller: digit2,
                                                    textAlign: TextAlign.center,
                                                    style: buildTextStyle(),
                                                    keyboardType: TextInputType.number,
                                                    decoration: buildInputDecoration(context),
                                                    onSaved: (val) {},
                                                    onFieldSubmitted: (_) {
                                                      FocusScope.of(context).requestFocus(focusD3);
                                                    },
                                                    onChanged: (val) {
                                                      if (val.length == 1) {
                                                        FocusScope.of(context).requestFocus(focusD3);
                                                        verifyAccountFormValue['digit2'] = val.trim();
                                                        //checkValue();
                                                      }
                                                    },
                                                    //validator: validateCodeDigit,
                                                  ),
                                                ),
                                                Container(
                                                    margin: EdgeInsets.all(5),
                                                    width: SizeConfig.realScreenWidth! * 0.16,
                                                    child: TextFormField(
                                                      focusNode: focusD3,
                                                      textInputAction: TextInputAction.next,
                                                      maxLength: 1,
                                                      controller: digit3,
                                                      textAlign: TextAlign.center,
                                                      style: buildTextStyle(),
                                                      keyboardType: TextInputType.number,
                                                      decoration: buildInputDecoration(context),
                                                      onSaved: (val) {},
                                                      onFieldSubmitted: (_) {
                                                        FocusScope.of(context).requestFocus(focusD4);
                                                      },
                                                      onChanged: (val) {
                                                        if (val.length == 1) {
                                                          FocusScope.of(context).requestFocus(focusD4);
                                                          verifyAccountFormValue['digit3'] = val.trim();
                                                          //checkValue();
                                                        }
                                                      },
                                                      // validator:
                                                      //     validateCodeDigit,
                                                    )),
                                                Container(
                                                    margin: EdgeInsets.all(5),
                                                    width: SizeConfig.realScreenWidth! * 0.16,
                                                    child: TextFormField(
                                                      focusNode: focusD4,
                                                      maxLength: 1,
                                                      textAlign: TextAlign.center,
                                                      style: buildTextStyle(),
                                                      controller: digit4,
                                                      keyboardType: TextInputType.number,
                                                      decoration: buildInputDecoration(context),
                                                      onFieldSubmitted: (_) {
                                                        FocusScope.of(context).requestFocus(focusD4);
                                                      },
                                                      onChanged: (val) {
                                                        if (val.length == 1) {
                                                          verifyAccountFormValue['digit4'] = val.trim();
                                                          //checkValue();
                                                        }
                                                      },
                                                      // validator:
                                                      //     validateCodeDigit,
                                                    )),
                                              ],
                                            )),
                                      ),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(12.0),
                                      child: Column(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [
                                        AppText(
                                          TranslationBase.of(context).validationMessage + ' ',
                                          fontWeight: FontWeight.w600,
                                          fontSize: 14,
                                        ),
                                        // AppText(
                                        //   displayTime,
                                        //   color: Colors.red,
                                        //   textAlign: TextAlign.start,
                                        //   fontWeight: FontWeight.bold,
                                        //   fontSize: 14,
                                        // )
                                      ]),
                                    )
                                  ],
                                ))),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
            )
          ],
        ),
        bottomSheet: isSendOtp
            ? Container(
                height: 60,
                margin: EdgeInsets.symmetric(vertical: 16, horizontal: 16),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        child: AppButton(
                          title: TranslationBase.of(context).cancel,
                          hasBorder: true,
                          vPadding: 12,
                          hPadding: 8,
                          borderColor: Color(0xFFeaeaea),
                          color: Color(0xFFeaeaea),
                          fontColor: Colors.black,
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                    Expanded(
                      child: Container(
                        child: AppButton(
                          title: TranslationBase.of(context).next,
                          hasBorder: true,
                          vPadding: 12,
                          hPadding: 8,
                          borderColor: Color(0xFFB8382B),
                          color: HexColor("#D02127"),
                          fontColor: Colors.white,
                          onPressed: () async {
                            GifLoaderDialogUtils.showMyDialog(context);
                            await widget.model!.checkActivationCode("${digit1.text}${digit2.text}${digit3.text}${digit4.text}");
                            if (widget.model!.state == ViewState.ErrorLocal) {
                              Utils.showErrorToast(widget.model!.error);
                              //TODO Elham* remove this
                              widget.changePageViewIndex!(2);
                              GifLoaderDialogUtils.hideDialog(context);
                            } else {
                              GifLoaderDialogUtils.hideDialog(context);
                              widget.changePageViewIndex!(2);
                            }
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              )
            : SizedBox());
  }

  sendActivationCode(type) async {
    GifLoaderDialogUtils.showMyDialog(context);
    await widget.model!.sendActivationCodeByOTPNotificationType(otpType: type);

    if (widget.model!.state == ViewState.ErrorLocal) {
      Utils.showErrorToast(widget.model!.error);
      GifLoaderDialogUtils.hideDialog(context);
      // TODO Elham* retuen the else
      setState(() {
        isSendOtp = false;
      });
    } else {
      setState(() {
        isSendOtp = true;
      });
    }
  }

  InputDecoration buildInputDecoration(BuildContext context) {
    return InputDecoration(
      counterText: " ",
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        borderSide: BorderSide(color: Colors.red),
      ),
    );
  }
}
