import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/model/family-file/add_family_file_request.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/theme/colors.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/confirm_dialog.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/progress_indicator/app_circular_progress_Indeicator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'add-family_type.dart';

class AddMember extends StatefulWidget {
  @override
  _AddMember createState() => _AddMember();
}

class _AddMember extends State<AddMember> {
  final util = Utils();
  final nationalIDorFile = TextEditingController();
  final int loginType = AddFamilyMemberType.loginType;
  String mobileNo;
  String countryCode = '966';
  bool isButtonDisabled = true;
  var sharedPref = new AppSharedPreferences();
  final authService = new AuthProvider();
  bool isLoading = false;
  var familyFileProvider = FamilyFilesProvider();

  var patientShareRequestID;
  var patientShareResponseID;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).myFamilyFiles,
      isShowAppBar: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      body: isLoading == true
          ? AppCircularProgressIndicator()
          : SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.all(21.0),
                height: SizeConfig.realScreenHeight * .9,
                width: SizeConfig.realScreenWidth,
                child: Column(
                  children: <Widget>[
                    Expanded(
                        flex: 1,
                        child: Text(
                          loginType == 1 ? TranslationBase.of(context).enterNationalId : TranslationBase.of(context).enterFile,
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.64, height: 23 / 16),
                        )),
                    Expanded(
                      flex: 4,
                      child: Column(
                        children: <Widget>[
                          PhoneNumberSelectorWidget(onNumberChange: (value) => {mobileNo = value, validateForm()}, onCountryChange: (value) => countryCode = value),
                          SizedBox(
                            height: 12,
                          ),
                          inputWidget(loginType == 1 ? TranslationBase.of(context).nationalIdNumber : TranslationBase.of(context).medicalFileNumber, "Xxxxxxxxx", nationalIDorFile),
                        ],
                      ),
                    ),
                    // Expanded(
                    //   flex: 3,
                    //   child: Column(
                    //     mainAxisAlignment: MainAxisAlignment.end,
                    //     children: <Widget>[
                    //       Row(
                    //         children: <Widget>[
                    //           Expanded(
                    //             child: DefaultButton(
                    //               TranslationBase.of(context).add,
                    //               () => {this.addMember()},
                    //               color: isButtonDisabled == true ? Colors.grey : CustomColors.accentColor,
                    //               textColor: Colors.white,
                    //             ),
                    //           )
                    //         ],
                    //       ),
                    //     ],
                    //   ),
                    // )
                  ],
                ),
              ),
            ),
      bottomSheet: Container(
          color: Colors.white,
          padding: EdgeInsets.all(21.0),
          child: DefaultButton(
            TranslationBase.of(context).add,
            () => {this.addMember()},
            color: isButtonDisabled == true ? Colors.grey : CustomColors.accentColor,
            textColor: Colors.white,
          )),
    );
  }

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

  addMember() {
    var request = AddFamilyFileReq();
    if (this.loginType == 1) {
      request.sharedPatientID = 0;
      request.sharedPatientIdentificationID = this.nationalIDorFile.text;
    } else if (this.loginType == 2) {
      request.sharedPatientID = int.parse(this.nationalIDorFile.text);
      request.sharedPatientIdentificationID = '';
    }
    request.searchType = this.loginType;
    request.sharedPatientMobileNumber = this.mobileNo;
    request.zipCode = countryCode;
    request.isRegister = false;
    request.patientStatus = 2;
    loading(true);
    familyFileProvider.addFamilyFile(request).then((value) => manageFamily(value)).catchError((err) {
      loading(false);
    });
  }

  manageFamily(addMemberResult) {
    loading(false);
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: addMemberResult['ShareFamilyFileObj']['Message'],
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () => {insertFamilyData(addMemberResult), ConfirmDialog.closeAlertDialog(context)},
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  insertFamilyData(addMemberResult) {
    sendActivationCode(addMemberResult);
    // var request = InsertSharePatientFileReq();
    // request.responseID = addMemberResult['ShareFamilyFileObj']['ReponseID'];
    // request.shareFamilyPatientName = addMemberResult['ShareFamilyFileObj']['SharedPatientName'];
    // request.status = 2;
    // if (request.patientOutSA == 1) {
    //   request.regionID = 2;
    // } else {
    //   request.regionID = 1;
    // }
    // loading(true);
    // familyFileProvider.insertNewMember(request).then((value) => sendActivationCode(value)).catchError((err) {
    //   loading(false);
    //   AppToast.showErrorToast(message: err);
    // });
  }

  sendActivationCode(result) {
    // var request = this.getCommonRequest();
    loading(true);
    patientShareResponseID = result['ShareFamilyFileObj']['ReponseID'];
    familyFileProvider.sendActivationCode(mobileNo, countryCode, nationalIDorFile.text, patientShareResponseID).then((res) => {
          patientShareRequestID = res['PatientShareRequestID'],
          if (res != null && res['isSMSSent'] == true) {this.startSMSService(1, res)}
        });
  }

  var tempType;

  startSMSService(type, result) {
    tempType = type;
    loading(false);
    SMSOTP(
      context,
      type,
      mobileNo,
      (value) {
        this.checkActivationCode(value, result);
      },
      () => {
        Navigator.pop(context),
      },
    ).displayDialog(context);
  }

  checkActivationCode(value, result) {
    Navigator.pop(context);
    GifLoaderDialogUtils.showMyDialog(context);
    familyFileProvider.checkActivationCode(result['LogInTokenID'], value, nationalIDorFile.text, mobileNo, patientShareRequestID, patientShareResponseID).then((result) {
      SMSOTP.hideSMSBox(context);
      handleFamilyRequests(this.patientShareRequestID, 3);
    }).catchError((err) {
      Future.delayed(Duration(seconds: 1), () {
        AppToast.showErrorToast(message: err);
        startSMSService(tempType, result);
      });
    });
  }

  handleFamilyRequests(id, stauts) {
    // familyFileProvider.acceptAndRejectRecievedRequests(id, stauts).then((result) => {
    sharedPref.remove(FAMILY_FILE);
    Navigator.of(context).pushNamed(
      MY_FAMILIY,
    );
    // });
  }

  loading(flag) {
    setState(() {
      isLoading = flag;
    });
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: TextInputType.number,
                    controller: _controller,
                    onChanged: (value) => {validateForm()},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }
}
