import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/core/model/family-file/add_family_file_request.dart';
import 'package:diplomaticquarterapp/core/model/family-file/insert_share_file_request.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/pages/family/add-family_type.dart';
import 'package:diplomaticquarterapp/services/family_files/family_files_provider.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.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/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/otp/sms-popup.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:diplomaticquarterapp/config/shared_pref_kay.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;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
        appBarTitle: TranslationBase.of(context).myFamilyFiles,
        isShowAppBar: true,
        body: isLoading == true
            ? AppCircularProgressIndicator()
            : 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: 2,
                      child: AppText(
                        TranslationBase.of(context).enterNationalId,
                        fontSize: SizeConfig.textMultiplier * 3.5,
                        textAlign: TextAlign.left,
                      )),
                  Expanded(
                    flex: 3,
                    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()},
                          prefixIcon: Icon(
                              loginType == 1
                                  ? Icons.chrome_reader_mode
                                  : Icons.receipt,
                              color: Colors.red),
                          padding: EdgeInsets.only(
                              top: 20, bottom: 20, left: 10, right: 10),
                          hintText: loginType == 1
                              ? TranslationBase.of(context).nationalID
                              : TranslationBase.of(context).fileNo,
                        ))
                      ],
                    ),
                  ),
                  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
                                    : Colors.grey[900],
                                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(() {
      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) {
    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);
    this
        .familyFileProvider
        .insertNewMember(request)
        .then((value) => sendActivationCode(value));
  }

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

  startSMSService(type, result) {
    loading(false);
    new SMSOTP(
      context,
      type,
      this.mobileNo,
      (value) => {this.checkActivationCode(value, result)},
      () => {
        print('Faild..'),
      },
    ).displayDialog(context);
  }

  checkActivationCode(value, result) {
    this
        .familyFileProvider
        .checkActivationCode(
            result['LogInTokenID'], value, nationalIDorFile.text, mobileNo)
        .then((result) => {
              SMSOTP.hideSMSBox(context),
              handleFamilyRequests(this.patientShareRequestID, 3)
            });
  }

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

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