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_cities_response_model.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/dialogs/select_country_ingo_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/widgets/bottom_options/BottomSheet.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';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../dialogs/select_city_dialog.dart';


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

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

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

class _NewEReferralStepTowPageState extends State<NewEReferralStepTowPage> {
  TextEditingController _patientNameTextController = TextEditingController();
  TextEditingController _patientIdentificationTextController = TextEditingController();
  TextEditingController _mobileTextController = TextEditingController();
  GetAllCitiesResponseModel _selectedCity  ;
  GetAllSharedRecordsByStatusList selectedPatientFamily;

  // 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) {
    return BaseView<EReferralViewModel>(
        onModelReady: (model) => model.getAllCities(),
        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: 30,
                        ),
                        Center(
                          child: Texts(
//                        TranslationBase.of(context).advancePaymentLabel,
                            "Patient information",
                            textAlign: TextAlign.center,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        NewTextFields(
                          hintText: "Enter Identification Number",
                          controller: _patientIdentificationTextController,
                          keyboardType:TextInputType.number ,
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        NewTextFields(
                          hintText: "Enter Patient Name",
                          controller: _patientNameTextController,
                        ),
                        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,
                            "Where the patient located",
                            textAlign: TextAlign.center,
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        InkWell(
                          onTap: () => confirmSelectCityDialog(
                              model.allCities),
                          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)
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),

                        SizedBox(
                          height: 12,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            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 {
                  this.widget.changePageViewIndex(2);
                  this.widget.createEReferralRequestModel.identificationNo = int.parse( _patientIdentificationTextController.text);
                  this.widget.createEReferralRequestModel.fullName = _patientNameTextController.text;
                  this.widget.createEReferralRequestModel.patientMobileNumber = _selectedCountry['code'].toString().substring(1)+_mobileTextController.text;
                  this.widget.createEReferralRequestModel.cityCode = _selectedCity.iD.toString();
                  this.widget.createEReferralRequestModel.cityName = _selectedCity.description;


                },
                loading: model.state == ViewState.BusyLocal,
                disabled:
                _patientNameTextController.text.isEmpty || _patientIdentificationTextController.text.isEmpty||
                    _selectedCity == null ||
                    _mobileTextController.text.isEmpty,
              ),
            )));


  }

  void confirmSelectCityDialog(
      List<GetAllCitiesResponseModel> cities) {
    showDialog(
      context: context,
      child: SelectCityDialog(
        cities: cities,
        selectedCity: _selectedCity,
        onValueSelected: (value) {
          setState(() {
            _selectedCity = value;
          });
        },
      ),
    );
  }

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

  String getRelationName() {
    if (_selectedCity != null)
      return _selectedCity.description;
    else
      return "Select City" /*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: 'Mobile No'),
            ),
          ),
        )
      ]),
    );
  }
}
