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/viewModels/medical/my_balance_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/AlHabibMedicalService/h2o/h20_setting.dart';
import 'package:diplomaticquarterapp/pages/Blood/user_agreement_page.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/theme/colors.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/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/show_zoom_image_dialog.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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> {
  BeneficiaryType beneficiaryType = BeneficiaryType.NON;

  CitiesModel _selectedHospital;

  int _selectedHospitalIndex = 0;
  int _selectedGenderIndex = 1;
  int _selectedBloodTypeIndex = 0;
  String _selectedBloodType = "O+";

  String amount = "";
  String email;

  List_BloodGroupDetailsModel bloodDetails = List_BloodGroupDetailsModel(bloodGroup: "A-");
  AppSharedPreferences sharedPref = AppSharedPreferences();
  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((_) {});
    super.initState();
  }

  int getSelectedCityID(MyBalanceViewModel model) {
    int cityID = 1;
    model.CitiesModelList.forEach((element) {
      if (element.description == model.bloodModelList[0].city) {
        cityID = element.iD;
      }
    });
    return cityID;
  }

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

    return BaseView<MyBalanceViewModel>(
      onModelReady: (model) => model.getCities().then((value) {
        model.getBlood().then((value) {
          if (model.bloodModelList.length > 0) {
            CitiesModel citiesModel = new CitiesModel();
            citiesModel.iD = getSelectedCityID(model);
            _selectedHospitalIndex = (citiesModel.iD - 1);
            citiesModel.description = model.CitiesModelList[_selectedHospitalIndex].description;
            citiesModel.descriptionN = model.CitiesModelList[_selectedHospitalIndex].descriptionN;
            _selectedHospital = citiesModel;
            _selectedBloodType = model.bloodModelList[0].bloodGroup;
            _selectedBloodTypeIndex = getBloodIndex(_selectedBloodType);
          } else {
            _selectedHospital = model.CitiesModelList[0];
          }
        });
      }),
      // {
      //   if (projectProvider.isLogin && projectProvider.user != null) {
      //     model.getCities().then((value) {
      //       model.getBlood().then((value) {
      //         if (model.bloodModelList.length > 0) {
      //           CitiesModel citiesModel = new CitiesModel();
      //           citiesModel.iD = getSelectedCityID(model);
      //           _selectedHospitalIndex = (citiesModel.iD - 1);
      //           citiesModel.description = model.CitiesModelList[_selectedHospitalIndex].description;
      //           citiesModel.descriptionN = model.CitiesModelList[_selectedHospitalIndex].descriptionN;
      //           _selectedHospital = citiesModel;
      //           _selectedBloodType = model.bloodModelList[0].bloodGroup;
      //           _selectedBloodTypeIndex = getBloodIndex(_selectedBloodType);
      //         } else {
      //           _selectedHospital = model.CitiesModelList[0];
      //         }
      //       });
      //     });
      //   }
      // },
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        showNewAppBar: true,
        backgroundColor: Color(0xffF7F7F7),
        showNewAppBarTitle: true,
        baseViewModel: model,
        isShowDecPage: true,
        imagesInfo: imagesInfo,
        description: TranslationBase.of(context).bloodDonationInfo,
        appBarTitle: TranslationBase.of(context).bloodD,
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                padding: EdgeInsets.all(21),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      TranslationBase.of(context).bloodDEnterDesc,
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64),
                    ),
                    SizedBox(height: 12),
                    if (projectProvider.isLogin && model.state != ViewState.Busy)

                      CommonDropDownView(
                        TranslationBase.of(context).city,
                        model.CitiesModelList.isNotEmpty
                            ? projectProvider.isArabic
                            ? model.CitiesModelList[_selectedHospitalIndex].descriptionN
                            : model.CitiesModelList[_selectedHospitalIndex].description
                            : "", () {
                      List<RadioSelectionDialogModel> list = [
                        for (int i = 0; i < model.CitiesModelList.length; i++)
                          RadioSelectionDialogModel(projectProvider.isArabic ? model.CitiesModelList[i].descriptionN : model.CitiesModelList[i].description, i),
                      ];

                      showDialog(
                        context: context,
                        builder: (cxt) => RadioSelectionDialog(
                          listData: list,
                          selectedIndex: _selectedHospitalIndex,
                          isScrollable: true,
                          onValueSelected: (index) {
                            _selectedHospitalIndex = index;
                            _selectedHospital = model.CitiesModelList[index];
                            setState(() {});
                          },
                        ),
                      );
                    }).withBorderedContainer,
                    SizedBox(height: 12),
                    CommonDropDownView(TranslationBase.of(context).gender, _selectedGenderIndex == 1 ? TranslationBase.of(context).male : TranslationBase.of(context).female, () {
                      List<RadioSelectionDialogModel> list = [
                        RadioSelectionDialogModel(TranslationBase.of(context).male, 1),
                        RadioSelectionDialogModel(TranslationBase.of(context).female, 2),
                      ];

                      showDialog(
                        context: context,
                        builder: (cxt) => RadioSelectionDialog(
                          listData: list,
                          selectedIndex: _selectedGenderIndex,
                          onValueSelected: (index) {
                            _selectedGenderIndex = index;
                            setState(() {});
                          },
                        ),
                      );
                    }).withBorderedContainer,
                    SizedBox(height: 12),
                    CommonDropDownView(TranslationBase.of(context).bloodType, _selectedBloodType, () {
                      List<RadioSelectionDialogModel> list = [
                        RadioSelectionDialogModel("O+", 0),
                        RadioSelectionDialogModel("O-", 1),
                        RadioSelectionDialogModel("AB+", 2),
                        RadioSelectionDialogModel("AB-", 3),
                        RadioSelectionDialogModel("A+", 4),
                        RadioSelectionDialogModel("A-", 5),
                        RadioSelectionDialogModel("B+", 6),
                        RadioSelectionDialogModel("B-", 7),
                      ];

                      showDialog(
                        context: context,
                        builder: (cxt) => RadioSelectionDialog(
                          listData: list,
                          selectedIndex: _selectedBloodTypeIndex,
                          isScrollable: true,
                          onValueSelected: (index) {
                            _selectedBloodTypeIndex = index;
                            _selectedBloodType = getBlood(index);
                            setState(() {});
                          },
                        ),
                      );
                    }).withBorderedContainer,
                    SizedBox(height: 12),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          TranslationBase.of(context).viewTermsConditions + ":",
                          style: TextStyle(fontWeight: FontWeight.w600, color: Color(0xff2E303A), fontSize: 14, letterSpacing: -0.56),
                        ),
                        InkWell(
                          onTap: () {
                            Navigator.of(context).push(FadePage(page: UserAgreementPage()));
                          },
                          child: Text(
                            TranslationBase.of(context).clickHere,
                            style: TextStyle(fontWeight: FontWeight.w600, color: Colors.blue, fontSize: 14, letterSpacing: -0.56),
                          ),
                        )
                      ],
                    ),
                    SizedBox(height: 12),
                    Row(
                      children: [
                        Checkbox(
                          onChanged: (bool value) {
                            setState(() {
                              checkedValue = value;
                            });
                          },
                          value: checkedValue,
                          activeColor: Color(0xFFc5272d),
                        ),
                        Text(
                          TranslationBase.of(context).iAgreeToTheTermsAndConditions,
                          style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Center(
                          child: Container(
                            color: Theme.of(context).primaryColor,
                            width: 350,
                            child: InkWell(
                              onTap: () {
                                showZoomImageDialog(context, 'assets/images/BloodChrt_EN.png', isNetworkImage: false);
                              },
                              child: Container(width: 250, height: 200, child: Image.asset('assets/images/BloodChrt_EN.png'), color: Colors.white),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.15,
                    )
                  ],
                ),
              ),
            ),
            DefaultButton(
              TranslationBase.of(context).save,
              checkedValue
                  ? () async {
                      if (_selectedHospital == null) {
                        AppToast.showErrorToast(message: TranslationBase.of(context).selectCity);
                        return;
                      }
                      bloodDetails.city = _selectedHospital.description;
                      bloodDetails.cityCode = _selectedHospital.iD.toString();
                      bloodDetails.gender = _selectedGenderIndex;
                      bloodDetails.bloodGroup = getBlood(_selectedBloodTypeIndex);
                      await model.updateBloodGroup(bloodDetails);
                      if (model.state == ViewState.Idle) {
                        AppToast.showSuccessToast(message: model.updatedRegisterBloodMessage);
                      } else {
                        AppToast.showErrorToast(message: model.error);
                      }
                    }
                  : null,
              disabledColor: CustomColors.grey2,
            ).insideContainer
          ],
        ),
      ),
    );
  }

  String getBlood(int index) {
    switch (index) {
      case 0:
        return "O+";
        break;
      case 1:
        return "O-";
        break;
      case 2:
        return "AB+";
        break;
      case 3:
        return "AB-";
        break;
      case 4:
        return "A+";
        break;
      case 5:
        return "A-";
        break;
      case 6:
        return "B-";
        break;
      case 7:
        return "B-";
        break;
      case 8:
        return "B+";
        break;

      default:
        return "";
    }
  }

  int getBloodIndex(String type) {
    switch (type) {
      case "O+":
        return 0;
        break;
      case "O-":
        return 1;
        break;
      case "AB+":
        return 2;
        break;
      case "AB-":
        return 3;
        break;
      case "A+":
        return 4;
        break;
      case "A-":
        return 5;
        break;
      case "B-":
        return 6;
        break;
      case "B-":
        return 7;
        break;
      case "B+":
        return 8;
        break;

      default:
        return 0;
    }
  }

  String getHospitalName(ProjectViewModel projectProvider, BuildContext context) {
    if (_selectedHospital != null)
      return projectProvider.isArabic ? _selectedHospital.descriptionN : _selectedHospital.description;
    else
      return TranslationBase.of(context).selectCity;
  }
}
