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/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.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/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/mobile-no/mobile_no.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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();
  String mobileNo = "";
  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,
        backgroundColor: CustomColors.appBackgroudGrey2Color,
        body: 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).patientInfo,
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.64,
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),
                      inputWidget(TranslationBase.of(context).enterIdentificationNumber, "", _patientIdentificationTextController, isInputTypeNum: true),
                      SizedBox(
                        height: 12,
                      ),
                      inputWidget(TranslationBase.of(context).patientName, "", _patientNameTextController, isInputTypeNum: false),
                      SizedBox(
                        height: 12,
                      ),
                      PhoneNumberSelectorWidget(onNumberChange: (value) {
                        setState(() {
                          mobileNo = value;
                        });
                      }, onCountryChange: (value) {
                        setState(() {
                          _selectedCountry = value;
                        });
                      }),
                      SizedBox(
                        height: 12,
                      ),
                      Text(
                        TranslationBase.of(context).patientLocated,
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.64,
                        ),
                      ),
                      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: () => confirmSelectCityDialog(model.allCities),
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      TranslationBase.of(context).selectCity,
                                      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,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.zero,
              decoration: cardRadius(0),
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.all(12),
                child: DefaultButton(
                  TranslationBase.of(context).next,
                  (_patientNameTextController.text.isEmpty || _patientIdentificationTextController.text.isEmpty || _selectedCity == null || mobileNo.isEmpty)
                      ? null
                      : () {
                          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() + mobileNo;
                          this.widget.createEReferralRequestModel.cityCode = _selectedCity.iD.toString();
                          this.widget.createEReferralRequestModel.cityName = _selectedCity.description;
                        },
                  disabledColor: Colors.grey,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  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 confirmSelectCityDialog(List<GetAllCitiesResponseModel> cities) {
    showDialog(
      context: context,
      builder: (cxt) => SelectCityDialog(
        cities: cities,
        selectedCity: _selectedCity,
        onValueSelected: (value) {
          setState(() {
            _selectedCity = value;
          });
        },
      ),
    );
  }

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

  String getRelationName() {
    if (_selectedCity != null)
      return _selectedCity.description;
    else
      return TranslationBase.of(context).selectCity /*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: TranslationBase.of(context).mobileNumber),
            ),
          ),
        )
      ]),
    );
  }
}
