import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/search_criteria_model.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/EReferral/search_e_referral_request_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/all_habib_medical_services/e_referral_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/medical/balance/new_text_Field.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/errors/app_embedded_error.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/others/network_base_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'New_E_Referral/new_e_referral_step_one_page.dart';
import 'dialogs/select_country_ingo_Dialog.dart';
import 'dialogs/select_search_criteria_dialog.dart';

class SearchForReferralsPage extends StatefulWidget {
  SearchForReferralsPage({Key key});

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

class _SearchForReferralsPageState extends State<SearchForReferralsPage> {
  TextEditingController _searchTextController = TextEditingController();

  TextEditingController _mobileTextController = TextEditingController();
  bool _isSubmitted = false;

  dynamic _selectedCountry = {
    "name": "Saudi Arabia",
    "name_ar": "المملكة العربية السعودية",
    "code": "+966",
    "countryCode": "SA",
    "pattern": "5xxxxxxxx",
    "maxLength": 9
  };

  SearchCriteriaModel selectedCriteria = SearchCriteriaModel(
      name: "Identification Number", nameAr: "رقم المحول", value: 1);

  @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: 77,
                        ),
                        InkWell(
                          onTap: () => selectSearchCriteriaDialog(),
                          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(getSearchCriteriaName()),
                                Icon(Icons.arrow_drop_down)
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: 12,
                        ),
                        NewTextFields(
                          hintText: selectedCriteria.value == 1
                              ? "Enter Patient Identification No"
                              : "Enter Referral Number",
                          controller: _searchTextController,
                        ),
                        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,
                        ),
                        if ((model.state == ViewState.Idle &&
                            model.allReferral.length == 0))
                          Text("There's No Referral To deliver"),
                        if ((
                            model.state == ViewState.ErrorLocal))
                          AppEmbeddedError( error:model.error),
                        NetworkBaseView(
                          baseViewModel: model,
                          child: ListView.builder(
                            shrinkWrap: true,
                            scrollDirection: Axis.vertical,
                            itemCount: model.allReferral == null
                                ? 0
                                : model.allReferral.length < 3
                                    ? model.allReferral.length
                                    : 3,
                            itemBuilder: (BuildContext context, int index) {
                              return Padding(
                                padding: EdgeInsets.symmetric(horizontal: 0.2),
                                child: Container(
                                  child: Texts("TODO  add referral info"),
                                ),
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            bottomSheet: Container(
              height: MediaQuery.of(context).size.height * 0.1,
              width: double.infinity,
              padding: EdgeInsets.all(9),
              child: SecondaryButton(
                textColor: Colors.white,
                label: "Search",
                onTap: () async {
                  SearchEReferralRequestModel searchEReferralRequestModel =
                      new SearchEReferralRequestModel(
                    patientMobileNumber:
                        _selectedCountry['code'] + _mobileTextController.text,
                  );
                  if (selectedCriteria.value == 1) {
                    searchEReferralRequestModel.identificationNo =
                        _searchTextController.text;
                    searchEReferralRequestModel.referralNumber = 0;
                  } else {
                    searchEReferralRequestModel.referralNumber =
                        int.parse(_searchTextController.text);
                    searchEReferralRequestModel.identificationNo = '';
                  }
                  await model.getEReferrals(searchEReferralRequestModel);
                  setState(() {
                    _isSubmitted = true;
                  });
                },
                loading: model.state == ViewState.BusyLocal,
                disabled: _searchTextController.text.isEmpty ||
                    _mobileTextController.text.isEmpty,
              ),
            )));
  }

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

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

  void selectSearchCriteriaDialog() {
    showDialog(
      context: context,
      child: SelectSearchCriteriaDialog(
        selectedCriteria: selectedCriteria,
        onValueSelected: (value) {
          setState(() {
            selectedCriteria = value;
          });
        },
      ),
    );
  }

  String getSearchCriteriaName() {
    return selectedCriteria.name;
  }
}
