import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/model/blooddonation/blood_groub_details.dart';
import 'package:diplomaticquarterapp/core/model/blooddonation/get_all_cities.dart';

//import 'package:diplomaticquarterapp/core/model/hospitals/hospitals_model.dart';
import 'package:diplomaticquarterapp/core/model/my_balance/AdvanceModel.dart';
import 'package:diplomaticquarterapp/core/model/my_balance/patient_info.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/my_balance_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/Blood/user_agreement_page.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/medical/balance/dialogs/SelectCiteisDialog.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.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:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:giffy_dialog/giffy_dialog.dart';
import 'package:provider/provider.dart';

import 'dialogs/SelectBeneficiaryDialog.dart';
import 'dialogs/SelectBloodDialog.dart';
import 'dialogs/SelectGenderDialog.dart';
import 'dialogs/SelectPatientFamilyDialog.dart';
import 'dialogs/SelectPatientInfoDialog.dart';

enum BeneficiaryType { MyAccount, MyFamilyFiles, OtherAccount, NON }
enum Gender { Male, Female, NON }
enum Blood { Oplus, Ominus, Aplus, Aminus, Bplus, Bminus, ABplus, ABminus, NON }

class BloodDonationPage extends StatefulWidget {
  @override
  _BloodDonationPageState createState() => _BloodDonationPageState();
}

class _BloodDonationPageState extends State<BloodDonationPage> {
  TextEditingController _fileTextController = TextEditingController();
  TextEditingController _notesTextController = TextEditingController();
  BeneficiaryType beneficiaryType = BeneficiaryType.NON;
  Gender gender = Gender.Male; //Gender.NON;
  Blood blood = Blood.Aminus; //Blood.NON;
  //HospitalsModel _selectedHospital;
  CitiesModel _selectedHospital;

  String amount = "";
  String email;
  PatientInfo _selectedPatientInfo;
  AuthenticatedUser authenticatedUser;
  GetAllSharedRecordsByStatusList selectedPatientFamily;
  AdvanceModel advanceModel = AdvanceModel();
  List_BloodGroupDetailsModel bloodDetails = List_BloodGroupDetailsModel(bloodGroup: "A-");
  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser;
  var checkedValue = false;
  List<ImagesInfo> imagesInfo = List();

  ProjectViewModel projectProvider;

  @override
  void initState() {
    imagesInfo.add(
      ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/blood/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/blood/ar/0.png'),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (projectProvider.isLogin) getAuthUser();
    });
    super.initState();
  }

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

    return BaseView<MyBalanceViewModel>(
      onModelReady: (model) => model.getCities(), //model.getHospitals(),
      builder: (_, model, w) => AppScaffold(
          isShowAppBar: true,
          baseViewModel: model,
          imagesInfo: imagesInfo,
          description: TranslationBase.of(context).bloodDonationInfo,
          appBarTitle: TranslationBase.of(context).bloodD,
          body: SingleChildScrollView(
            physics: ScrollPhysics(),
            child: Container(
              margin: EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Texts(
                    TranslationBase.of(context).bloodDEnterDesc,
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  InkWell(
                    onTap: () => confirmSelectHospitalDialog(model.CitiesModelList),
                    //model.hospitals
                    child: Container(
                      padding: EdgeInsets.all(12),
                      width: double.infinity,
                      height: 65,
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Theme.of(context).primaryColor),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [Texts(getHospitalName(projectProvider, context)), Icon(Icons.arrow_drop_down)],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  InkWell(
                    //======Gender========
                    onTap: () => confirmSelectGenderDialog(),
                    //confirmSelectBeneficiaryDialog(model),
                    child: Container(
                      padding: EdgeInsets.all(12),
                      width: double.infinity,
                      height: 65,
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Theme.of(context).primaryColor),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          //Texts(getBeneficiaryType()),
                          Texts(getGender(context)),
                          Icon(Icons.arrow_drop_down)
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  InkWell(
                    //======Gender========
                    onTap: () => confirmSelectBloodDialog(),
                    //confirmSelectBeneficiaryDialog(model),
                    child: Container(
                      padding: EdgeInsets.all(12),
                      width: double.infinity,
                      height: 65,
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Theme.of(context).primaryColor),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          //Texts(getBeneficiaryType()),
                          Texts(getBlood()),
                          Icon(Icons.arrow_drop_down)
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  Row(
                    children: [
                      Container(
                        child: Text(TranslationBase.of(context).viewTermsConditions),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.height * 0.10,
                      ),
                      InkWell(
                        onTap: () {
                          Navigator.of(context).push(FadePage(page: UserAgreementPage()));
                        },
                        child: Container(
                          child: Texts(
                            TranslationBase.of(context).clickHere,
                            color: Colors.blue,
                          ),
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  Row(
                    children: [
                      Checkbox(
                        onChanged: (bool value) {
                          setState(() {
                            checkedValue = value;
                          });
                        },
                        // tristate: checkedValue==true,//i == 1,
                        value: checkedValue,
                        activeColor: Color(0xFFc5272d), //Color(0xFF6200EE),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Row(
                        children: [],
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        TranslationBase.of(context).iAgreeToTheTermsAndConditions,
                        style: Theme.of(context).textTheme.subtitle1.copyWith(color: checkedValue ? Color(0xFFc5272d) : Colors.black),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Center(
                        child: Container(
                          color: Theme.of(context).primaryColor,
                          width: 350,
                          child: InkWell(
                            onTap: () {
                              showDialog(
                                  context: context,
                                  builder: (_) => AssetGiffyDialog(
                                        title: Text(
                                          "",
                                          style: TextStyle(fontSize: 22.0, fontWeight: FontWeight.w600),
                                        ),
                                        image: Image.asset('assets/images/BloodChrt_EN.png'),
                                        buttonCancelText: Text(TranslationBase.of(context).cancel),
                                        buttonCancelColor: Colors.grey,
                                        onlyCancelButton: true,
                                      ));
                            },
                            child: Container(width: 250, height: 200, child: Image.asset('assets/images/BloodChrt_EN.png')),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.15,
                  )
                ],
              ),
            ),
          ),
          bottomSheet: Container(
            height: MediaQuery.of(context).size.height * 0.12,
            width: double.infinity,
            padding: EdgeInsets.all(12),
            child: SecondaryButton(
              textColor: Colors.white,
              color: checkedValue == false
                  ? Color(0xFFa0a4a6)
                  : Color.fromRGBO(
                      63,
                      72,
                      74,
                      1,
                    ),
              label: TranslationBase.of(context).save,
              onTap: () async {
                if (_selectedHospital == null) {
                  AppToast.showErrorToast(message: TranslationBase.of(context).selectCity);
                  return;
                }
                bloodDetails.city = projectProvider.isArabic ? _selectedHospital.descriptionN : _selectedHospital.description;
                bloodDetails.cityCode = _selectedHospital.iD.toString();
                bloodDetails.gender = gender == Gender.Male ? 1 : 2;
                await model.updateBloodGroup(bloodDetails);
                if (model.state == ViewState.Idle) {
                  AppToast.showSuccessToast(message: model.updatedRegisterBloodMessage);
                } else {
                  AppToast.showErrorToast(message: model.error);
                }
              },
            ),
          )),
    );
  }

  //==============
  void confirmSelectBeneficiaryDialog(MyBalanceViewModel model) {
    showDialog(
      context: context,
      child: SelectBeneficiaryDialog(
        beneficiaryType: beneficiaryType,
        onValueSelected: (value) {
          setState(() {
            if (value == BeneficiaryType.MyAccount) {
              _fileTextController.text = model.user.patientID.toString();
              advanceModel.depositorName = model.user.firstName + " " + model.user.lastName;
            } else
              _fileTextController.text = "";

            beneficiaryType = value;
          });
        },
      ),
    );
  }

  void confirmSelectBloodDialog() {
    showDialog(
      context: context,
      child: SelectBloodDialog(
        bloodType: blood,
        onValueSelected: (value) {
          setState(() {
            if (value == Blood.Oplus) {
              bloodDetails.bloodGroup = "O+";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.Ominus) {
              // _fileTextController.text = model.user.patientID.toString();
              bloodDetails.bloodGroup = "O-";
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.ABplus) {
              bloodDetails.bloodGroup = "AB+";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.ABminus) {
              bloodDetails.bloodGroup = "AB-";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.Aplus) {
              bloodDetails.bloodGroup = "A+";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.Aminus) {
              bloodDetails.bloodGroup = "A-";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.Bplus) {
              bloodDetails.bloodGroup = "B+";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else if (value == Blood.Bminus) {
              bloodDetails.bloodGroup = "B-";
              // _fileTextController.text = model.user.patientID.toString();
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else
              _fileTextController.text = "";

            // beneficiaryType = value;
            blood = value;
          });
        },
      ),
    );
  }

  void confirmSelectGenderDialog() {
    showDialog(
      context: context,
      child: SelectGenderDialog(
        beneficiaryType: gender,
        onValueSelected: (value) {
          setState(() {
            if (value == Gender.Male) {
              // _fileTextController.text = model.user.patientID.toString();
              bloodDetails.patientType = 1;
              // advanceModel.depositorName =
              //     model.user.firstName + " " + model.user.lastName;
            } else
            // _fileTextController.text = "";
            {
              bloodDetails.gender = 2;
            }

            // beneficiaryType = value;
            gender = value;
          });
        },
      ),
    );
  }

//void confirmSelectHospitalDialog(List<HospitalsModel> hospitals) {
  void confirmSelectHospitalDialog(List<CitiesModel> hospitals) {
    showDialog(
      context: context,
      child: SelectCiteisDialog(
        hospitals: hospitals,
        selectedHospital: _selectedHospital,
        onValueSelected: (value) {
          setState(() {
            _selectedHospital = value;
          });
        },
      ),
    );
  }

  void confirmSelectPatientDialog(List<PatientInfo> patientInfoList) {
    showDialog(
      context: context,
      child: SelectPatientInfoDialog(
        patientInfoList: patientInfoList,
        selectedPatientInfo: _selectedPatientInfo,
        onValueSelected: (value) {
          setState(() {
            advanceModel.depositorName = value.fullName;
            _selectedPatientInfo = value;
          });
        },
      ),
    );
  }

  void confirmSelectFamilyDialog(List<GetAllSharedRecordsByStatusList> getAllSharedRecordsByStatusList) {
    showDialog(
      context: context,
      child: SelectPatientFamilyDialog(
        getAllSharedRecordsByStatusList: getAllSharedRecordsByStatusList,
        selectedPatientFamily: selectedPatientFamily,
        onValueSelected: (value) {
          setState(() {
            selectedPatientFamily = value;
            _fileTextController.text = selectedPatientFamily.patientID.toString();
            advanceModel.depositorName = value.patientName;
          });
        },
      ),
    );
  }

  String getBeneficiaryType() {
    switch (beneficiaryType) {
      case BeneficiaryType.MyAccount:
        return TranslationBase.of(context).myAccount;
      case BeneficiaryType.MyFamilyFiles:
        return TranslationBase.of(context).myFamilyFiles;
        break;
      case BeneficiaryType.OtherAccount:
        return TranslationBase.of(context).otherAccount;
        break;
      case BeneficiaryType.NON:
        return TranslationBase.of(context).selectBeneficiary;
    }
    return TranslationBase.of(context).selectBeneficiary;
  }

  String getGender(BuildContext context) {
    switch (gender) {
      case Gender.Male:
        return TranslationBase.of(context).male;
      case Gender.Female:
        return TranslationBase.of(context).female;
        break;

      case Gender.NON:
        return TranslationBase.of(context).selectGender;
    }
    return TranslationBase.of(context).selectGender;
  }

  String getBlood() {
    switch (blood) {
      case Blood.Oplus:
        return "O+";
        break;
      case Blood.Ominus:
        return "O-";
        break;
      case Blood.ABplus:
        return "AB+";
        break;
      case Blood.ABminus:
        return "AB-";
        break;
      case Blood.Aplus:
        return "A+";
        break;
      case Blood.Aminus:
        return "A-";
        break;
      case Blood.Bplus:
        return "B-";
        break;
      case Blood.Bminus:
        return "B-";
        break;
      case Blood.Bplus:
        return "B+";
        break;

      case Blood.NON:
        return "Select Blood Type"; //TranslationBase.of(context).selectBeneficiary;
    }
    return "Select Blood Type"; //TranslationBase.of(context).selectBeneficiary;
  }

  String getHospitalName(ProjectViewModel projectProvider, BuildContext context) {
    if (_selectedHospital != null)
      return projectProvider.isArabic ? _selectedHospital.descriptionN : _selectedHospital.description;
    else
      return TranslationBase.of(context).selectCity;
    // return List_BloodGroupDetailsModel.fromJson(0).city.toString();//"Select City";//TranslationBase.of(context).selectHospital;
  }

  String getPatientName() {
    if (_selectedPatientInfo != null)
      return _selectedPatientInfo.fullName;
    else
      return TranslationBase.of(context).selectPatientName;
  }

  getAuthUser() async {
    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }
  }

  String getFamilyMembersName() {
    if (selectedPatientFamily != null)
      return selectedPatientFamily.patientName;
    else
      return TranslationBase.of(context).selectFamilyPatientName;
  }

//================

}
