import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/create_e_referral_request_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/get_all_relationship_types_response_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/send_activation_code_for_e_referral_request_model.dart';
import 'package:diplomaticquarterapp/core/model/my_balance/AdvanceModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/all_habib_medical_services/e_referral_view_model.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/FamilyFiles/GetAllSharedRecordByStatusResponse.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/E-Referral/e_referral_confirm_sms_dialog.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/E-Referral/dialogs/select_country_ingo_Dialog.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/E-Referral/dialogs/select_relation_type_dialog.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/medical/balance/new_text_Field.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


class NewEReferralStepOnePage extends StatefulWidget {
  final CreateEReferralRequestModel createEReferralRequestModel;
  final Function changePageViewIndex;

  const NewEReferralStepOnePage({Key key, this.createEReferralRequestModel, this.changePageViewIndex}) : super(key: key);

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

class _NewEReferralStepOnePageState extends State<NewEReferralStepOnePage> {
  TextEditingController _nameTextController = TextEditingController();
  TextEditingController _mobileTextController = TextEditingController();
  GetAllRelationshipTypeResponseModel _selectedRelation;
  String email;
  AuthenticatedUser authenticatedUser;
  GetAllSharedRecordsByStatusList selectedPatientFamily;
  AdvanceModel advanceModel = AdvanceModel();

  // todo create a model for Country
  // todo use country from the json
  dynamic _selectedCountry = {
    "name": "Saudi Arabia",
    "name_ar": "المملكة العربية السعودية",
    "code": "+966",
    "countryCode": "SA",
    "pattern": "5xxxxxxxx",
    "maxLength": 9
  };
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser;

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

  @override
  Widget build(BuildContext context) {
    void showSMSDialog() {
      showDialog(
        context: context,
        barrierDismissible: false,
        child: EReferralConfirmSMSDialog(
          phoneNumber: _selectedCountry['code']+_mobileTextController.text,
          onSucces: (){
            Navigator.of(context).pop();
            widget.changePageViewIndex(1);
            widget.createEReferralRequestModel.requesterName=_nameTextController.text;
            widget.createEReferralRequestModel.requesterContactNo =  _selectedCountry['code'].toString().substring(1)+_mobileTextController.text;
            widget.createEReferralRequestModel.requesterRelationship=_selectedRelation.iD;


          }


        ),
      ).then((value) {
        print("dialog dismissed");
        print(value);
        if (value != null && value) {

        }
      });
    }
    return BaseView<EReferralViewModel>(
        onModelReady: (model) => model.getRelationTypes(),
        builder: (_, model, widget) => AppScaffold(
            isShowAppBar: false,
            body: SingleChildScrollView(
              physics: ScrollPhysics(),
              child: Container(
                margin: EdgeInsets.all(12),
                child: Center(
                  child: FractionallySizedBox(
                    widthFactor: 0.94,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 20,
                        ),
                        Center(
                          child: Texts(
//                        TranslationBase.of(context).advancePaymentLabel,
                            "Referral requester information",
                            textAlign: TextAlign.center,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        NewTextFields(
                          hintText: "Enter Referral Requester Name*",
                          controller: _nameTextController,
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        InkWell(
                          onTap: () => confirmSelectCountryTypeDialog(),
                          child: Container(
                            padding: EdgeInsets.all(12),
                            width: double.infinity,
                            height: 65,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(12),
                                color: Colors.white),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Texts(getCountryName()),
                                Icon(Icons.arrow_drop_down)
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        MobileNumberTextFiled(
                          controller: _mobileTextController,
                          code: _selectedCountry == null
                              ? "11"
                              : _selectedCountry["code"],
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        Center(
                          child: Texts(
//                        TranslationBase.of(context).advancePaymentLabel,
                            "Requester Relationship",
                            textAlign: TextAlign.center,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        InkWell(
                          onTap: () => confirmSelectRelationTypeDialog(
                              model.relationTypes),
                          child: Container(
                            padding: EdgeInsets.all(12),
                            width: double.infinity,
                            height: 65,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(12),
                                color: Colors.white),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Texts(getRelationName()),
                                Icon(Icons.arrow_drop_down)
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            bottomSheet: Container(
              height: MediaQuery
                  .of(context)
                  .size
                  .height * 0.1,
              width: double.infinity,
              padding: EdgeInsets.all(9),
              child: SecondaryButton(
                textColor: Colors.white,
                label: "Next",
                 onTap: () async {
                  SendActivationCodeForEReferralRequestModel sendActivationCodeForEReferralRequestModel =
                  SendActivationCodeForEReferralRequestModel(
                    zipCode: _selectedCountry['code'],
                    patientMobileNumber: int.parse(
                        _mobileTextController.text),);
                  await model.sendActivationCodeForEReferral(sendActivationCodeForEReferralRequestModel);

                  showSMSDialog();
                },
                loading: model.state == ViewState.BusyLocal,
                disabled:
                _nameTextController.text.isEmpty ||
                    _selectedRelation == null ||
                    _mobileTextController.text.isEmpty,
              ),
            )));


  }

  void confirmSelectRelationTypeDialog(
      List<GetAllRelationshipTypeResponseModel> relations) {
    showDialog(
      context: context,
      child: SelectRelationTypeDialog(
        relationTypes: relations,
        selectedRelation: _selectedRelation,
        onValueSelected: (value) {
          setState(() {
            _selectedRelation = value;
          });
        },
      ),
    );
  }

  void confirmSelectCountryTypeDialog() {
    showDialog(
      context: context,
      child: SelectCountryDialog(
        selectedCountry: _selectedCountry,
        onValueSelected: (value) {
          setState(() {
            _selectedCountry = value;
          });
        },
      ),
    );
  }

  String getRelationName() {
    if (_selectedRelation != null)
      return _selectedRelation.text;
    else
      return "Select Relationship" /*TranslationBase.of(context).selectHospital*/;
  }

  String getCountryName() {
    if (_selectedCountry != null)
      return _selectedCountry["name"];
    else
      return "Country";
  }
}

class MobileNumberTextFiled extends StatelessWidget {
  const MobileNumberTextFiled({
    Key key,
    this.controller,
    this.code
  }) : super(key: key);


  final TextEditingController controller;
  final String code;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(15), color: Colors.white),
      child: Row(children: <Widget>[
        Expanded(
            flex: 1,
            child: Icon(
              Icons.phone,
              color: Colors.red,
            )),
        Expanded(
            flex: 1,
            child: Text(
              code.toString(),
              overflow: TextOverflow.clip,
            )),
        Expanded(
          flex: 4,
          child: Container(
            margin: EdgeInsets.all(5),
            child: TextField(
              controller: controller,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                  border: InputBorder.none, hintText: '5xxxxxxxx'),
            ),
          ),
        )
      ]),
    );
  }
}
