import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/check_activation_code_for_e_referral_request_model.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/core/viewModels/project_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/dialogs/select_relation_type_dialog.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.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_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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 _requesterRelationTextController = TextEditingController();

  GetAllRelationshipTypeResponseModel _selectedRelation;
  String email;
  AuthenticatedUser authenticatedUser;
  GetAllSharedRecordsByStatusList selectedPatientFamily;
  AdvanceModel advanceModel = AdvanceModel();
  ProjectViewModel projectViewModel;
  String mobileNo = "";

  // 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();
  }

  void showSMSDialog(EReferralViewModel model) {
    SMSOTP(
      context,
      1,
      _selectedCountry['code'] + mobileNo,
      (value) {
        submit(model, value);
      },
      () => {
        Navigator.pop(context),
      },
    ).displayDialog(context);
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    return BaseView<EReferralViewModel>(
      onModelReady: (model) => model.getRelationTypes(),
      builder: (_, model, widget) => AppScaffold(
        isShowAppBar: false,
        backgroundColor: CustomColors.appBackgroudGrey2Color,
        body: Container(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  physics: ScrollPhysics(),
                  child: Container(
                    margin: EdgeInsets.all(12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 20,
                        ),
                        Text(
                          TranslationBase.of(context).referralRequesterInformation,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            letterSpacing: -0.64,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        inputWidget(TranslationBase.of(context).enterReferralRequesterName, "", _nameTextController, isInputTypeNum: false),
                        SizedBox(
                          height: 12,
                        ),
                        PhoneNumberSelectorWidget(onNumberChange: (value) {
                          setState(() {
                            mobileNo = value;
                          });
                        }, onCountryChange: (value) {
                          setState(() {
                            _selectedCountry = value;
                          });
                        }),
                        SizedBox(
                          height: 12,
                        ),
                        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: () => confirmSelectRelationTypeDialog(model.relationTypes),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        TranslationBase.of(context).selectRelationship,
                                        style: TextStyle(
                                          fontSize: 11,
                                          fontWeight: FontWeight.w600,
                                          color: Color(0xff2B353E),
                                          letterSpacing: -0.44,
                                        ),
                                      ),
                                      Text(
                                        getRelationName(),
                                        style: TextStyle(
                                          fontSize: 14,
                                          height: 21 / 14,
                                          fontWeight: FontWeight.w400,
                                          color: Color(0xff2B353E),
                                          letterSpacing: -0.44,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Icon(Icons.arrow_drop_down),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        if (_selectedRelation != null && _selectedRelation.iD == 5)
                          inputWidget(TranslationBase.of(context).requesterRelationship, "", _requesterRelationTextController, isInputTypeNum: false),
                      ],
                    ),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.zero,
                decoration: cardRadius(0),
                child: Container(
                  // color: Theme.of(context).scaffoldBackgroundColor,
                  padding: EdgeInsets.all(12),
                  width: double.infinity,
                  child: DefaultButton(
                    TranslationBase.of(context).next,
                    (_nameTextController.text.isEmpty || _selectedRelation == null || mobileNo.isEmpty || (_selectedRelation.iD == 5 && _requesterRelationTextController.text.isEmpty))
                        ? null
                        : () async {
                            Future.delayed(new Duration(milliseconds: 300)).then((value) async {
                              GifLoaderDialogUtils.showMyDialog(context);
                              SendActivationCodeForEReferralRequestModel sendActivationCodeForEReferralRequestModel = SendActivationCodeForEReferralRequestModel(
                                zipCode: _selectedCountry['code'],
                                patientMobileNumber: int.parse(mobileNo),
                              );
                              await model.sendActivationCodeForEReferral(sendActivationCodeForEReferralRequestModel);
                              GifLoaderDialogUtils.hideDialog(context);
                              showSMSDialog(model);
                            });
                          },
                    disabledColor: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void submit(EReferralViewModel model, code) async {
    final activationCode = code;
    Future.delayed(new Duration(milliseconds: 300)).then((value) async {
      GifLoaderDialogUtils.showMyDialog(context);
      CheckActivationCodeForEReferralResponseModel checkActivationCodeForEReferralRequestModel = new CheckActivationCodeForEReferralResponseModel(activationCode: activationCode);
      await model.checkActivationCodeForEReferral(checkActivationCodeForEReferralRequestModel);
      if (model.state == ViewState.ErrorLocal) {
        GifLoaderDialogUtils.hideDialog(context);
        Future.delayed(Duration(seconds: 1), () {
          AppToast.showErrorToast(message: model.error);
          showSMSDialog(model);
        });
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        Navigator.of(context).pop();
        widget.changePageViewIndex(1);
        widget.createEReferralRequestModel.requesterName = _nameTextController.text;
        widget.createEReferralRequestModel.requesterContactNo = _selectedCountry['code'].toString() + mobileNo;
        widget.createEReferralRequestModel.otherRelationship = _requesterRelationTextController.text;
        widget.createEReferralRequestModel.requesterRelationship = _selectedRelation.iD;
      }
    });
  }

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

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller,
      {VoidCallback suffixTap, bool isEnable = true, bool hasSelection = false, int lines, bool isInputTypeNum = 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: isInputTypeNum ? TextInputType.number : TextInputType.text,
                    controller: _controller,
                    maxLines: lines,
                    onChanged: (value) => {setState(() {})},
                    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,
                      ),
                      suffixIconConstraints: BoxConstraints(minWidth: 50),
                      suffixIcon: suffixTap == null ? null : IconButton(icon: Icon(Icons.mic, color: Color(0xff2E303A)), onPressed: suffixTap),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }

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

  String getRelationName() {
    if (_selectedRelation != null) {
      if (projectViewModel.isArabic) {
        return _selectedRelation.textAr;
      }
      return _selectedRelation.textEn;
    } else
      return "";
  }

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

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

  final TextEditingController controller;
  final String code;
  final Function onChange;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(15), color: Colors.white),
      child: Row(textDirection: TextDirection.ltr, 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,
              onChanged: onChange,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(border: InputBorder.none, hintText: '5xxxxxxxx'),
            ),
          ),
        )
      ]),
    );
  }
}
