import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/AlHabibMedicalService/EReferral/search_criteria_model.dart';
import 'package:hmg_patient_app/core/model/AlHabibMedicalService/EReferral/search_e_referral_request_model.dart';
import 'package:hmg_patient_app/core/viewModels/all_habib_medical_services/e_referral_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/E-Referral/referral_details.dart';
import 'package:hmg_patient_app/pages/AlHabibMedicalService/h2o/h20_setting.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/dialogs/radio_selection_dialog.dart';
import 'package:hmg_patient_app/widgets/errors/app_embedded_error.dart';
import 'package:hmg_patient_app/widgets/mobile-no/mobile_no.dart';
import 'package:hmg_patient_app/widgets/my_rich_text.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/others/network_base_view.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'dialogs/select_country_ingo_Dialog.dart';

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

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

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

  String mobileNo = "";
  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) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<EReferralViewModel>(
        onModelReady: (model) async {
          if (projectViewModel.isLogin) {
            Future.delayed(new Duration(milliseconds: 300)).then((value) async {
              GifLoaderDialogUtils.showMyDialog(context);
              SearchEReferralRequestModel searchEReferralRequestModel = new SearchEReferralRequestModel(
                patientMobileNumber: (projectViewModel.user!.outSA == 0 ? "966" : "971") + projectViewModel.user!.mobileNumber!.substring(1, projectViewModel.user!.mobileNumber!.length),
              );
              if (selectedCriteria.value == 1) {
                searchEReferralRequestModel.identificationNo = _searchTextController.text;
                searchEReferralRequestModel.referralNumber = 0;
              } else {
                searchEReferralRequestModel.referralNumber = int.parse(_searchTextController.text);
                searchEReferralRequestModel.identificationNo = projectViewModel.user!.patientIdentificationNo;
              }
              await model.getEReferrals(searchEReferralRequestModel);
              GifLoaderDialogUtils.hideDialog(context);
            });
          }
        },
        builder: (_, model, widget) => AppScaffold(
            isShowAppBar: false,
            baseViewModel: model,
            body: SingleChildScrollView(
              physics: ScrollPhysics(),
              child: Container(
                margin: EdgeInsets.all(12),
                child: Center(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 10,
                      ),
                      CommonDropDownView(TranslationBase.of(context).selectSearchCriteria, getSearchCriteriaName(projectViewModel), () {
                        List<SearchCriteriaModel> searchCriteria = [
                          SearchCriteriaModel(name: "Identification Number", nameAr: "رقم الهوية", value: 1),
                          SearchCriteriaModel(name: "Referral Number", nameAr: "رقم الإحالة", value: 2),
                        ];
                        List<RadioSelectionDialogModel> list = <RadioSelectionDialogModel>[];
                        for (int i = 0; i < searchCriteria.length; i++) {
                          list.add(RadioSelectionDialogModel(projectViewModel.isArabic ? searchCriteria[i].nameAr! : searchCriteria[i].name!, searchCriteria[i].value!));
                        }
                        showDialog(
                          context: context,
                          builder: (cxt) => RadioSelectionDialog(
                            listData: list,
                            selectedIndex: selectedCriteria.value,
                            onValueSelected: (index) {
                              selectedCriteria = searchCriteria[index - 1];
                              setState(() {});
                            },
                          ),
                        );
                      }).withBorderedContainer,
                      SizedBox(height: 12),
                      inputWidget(selectedCriteria.value == 1 ? TranslationBase.of(context).enterIdentificationNumber : TranslationBase.of(context).referralNumber, "", _searchTextController,
                          isInputTypeNum: true),
                      SizedBox(height: 12),
                      PhoneNumberSelectorWidget(onNumberChange: (value) {
                        setState(() {
                          mobileNo = value;
                        });
                      }, onCountryChange: (value) {
                        setState(() {
                          _selectedCountry = value;
                        });
                      }),
                      // 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,
                      //   onChange: (_) {
                      //     setState(() {});
                      //   },
                      //   code: _selectedCountry == null ? "11" : _selectedCountry["code"],
                      // ),
                      SizedBox(height: 12),
                      if ((model.state == ViewState.Idle && model.allReferral.length == 0)) Center(child: Text(TranslationBase.of(context).noSearchResult)),
                      if ((model.state == ViewState.ErrorLocal)) AppEmbeddedError(error: model.error),
                      model.allReferral.length > 0
                          ? NetworkBaseView(
                              baseViewModel: model,
                              child: ListView.separated(
                                separatorBuilder: (context, index) => SizedBox(height: 0),
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                itemCount: model.allReferral == null ? 0 : model.allReferral.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    width: double.infinity,
                                    child: InkWell(
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          FadePage(
                                            page: ReferralDetails(referral: model.allReferral[index]),
                                          ),
                                        );
                                      },
                                      child: Container(
                                        decoration: cardRadius(12),
                                        child: Padding(
                                          padding: const EdgeInsets.all(12.0),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Text(projectViewModel.isArabic ? model.allReferral[index].statusAr! : model.allReferral[index].status!,
                                                      style: TextStyle(fontSize: 14.0, letterSpacing: -0.56, fontWeight: FontWeight.bold)),
                                                  Container(
                                                      margin: EdgeInsets.only(top: 5.0),
                                                      child: MyRichText(TranslationBase.of(context).patientName + ": ", model.allReferral[index].patientName!, projectViewModel.isArabic)),
                                                  MyRichText(TranslationBase.of(context).hospital + ": ", model.allReferral[index].preferredBranchName!, projectViewModel.isArabic),
                                                  MyRichText(TranslationBase.of(context).referralDate + ": ",
                                                      DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDateNoTimeZone(model.allReferral[index].referralDate!)), projectViewModel.isArabic),
                                                ],
                                              ),
                                              Icon(projectViewModel.isArabic ? Icons.arrow_back_ios_outlined : Icons.arrow_forward_outlined),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                                },
                              ),
                            )
                          : Container(),
                      SizedBox(
                        height: 80.0,
                      )
                    ],
                  ),
                ),
              ),
            ),
            bottomSheet: Container(
              color: Theme.of(context).scaffoldBackgroundColor,
              width: double.infinity,
              padding: EdgeInsets.all(14),
              child: DefaultButton(
                TranslationBase.of(context).search,
                (_searchTextController.text.isEmpty || mobileNo.isEmpty)
                    ? null
                    : () async {
                        SearchEReferralRequestModel searchEReferralRequestModel = new SearchEReferralRequestModel(
                          patientMobileNumber: _selectedCountry['code'] + mobileNo,
                        );
                        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;
                        });
                      },
                disabledColor: Colors.grey,
              ),
            )));
  }

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

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

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller,
      {VoidCallback? suffixTap, bool isEnable = true, bool hasSelection = false, int? lines, bool isInputTypeNum = false}) {
    return 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),
        ],
      ),
    ).withBorderedContainer;
  }

  String getSearchCriteriaName(ProjectViewModel projectViewModel) {
    return projectViewModel.isArabic ? selectedCriteria.nameAr! : selectedCriteria.name!;
  }
}
