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/hospitals/hospitals_model.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/ToDoList/payment_method_select.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/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.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/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../core/model/my_balance/AdvanceModel.dart';
import 'confirm_payment_page.dart';
import 'new_text_Field.dart';

enum BeneficiaryType { MyAccount, MyFamilyFiles, OtherAccount, NON }

class AdvancePaymentPage extends StatefulWidget {
  @override
  _AdvancePaymentPageState createState() => _AdvancePaymentPageState();
}

class _AdvancePaymentPageState extends State<AdvancePaymentPage> {
  TextEditingController _fileTextController = TextEditingController();
  TextEditingController _notesTextController = TextEditingController();
  BeneficiaryType beneficiaryType = BeneficiaryType.NON;
  HospitalsModel _selectedHospital;
  String amount = "";
  String email;
  PatientInfo _selectedPatientInfo;
  AuthenticatedUser authenticatedUser;
  GetAllSharedRecordsByStatusList selectedPatientFamily;
  AdvanceModel advanceModel = AdvanceModel();

  AppSharedPreferences sharedPref = AppSharedPreferences();
  AuthenticatedUser authUser;

  List<ImagesInfo> imagesInfo = List();

  ProjectViewModel projectViewModel;

  @override
  void initState() {
    super.initState();
    getAuthUser();
    imagesInfo.add(ImagesInfo(
        imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/advance-payment/en/0.png',
        imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/advance-payment/ar/0.png'));
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return BaseView<MyBalanceViewModel>(
      onModelReady: (model) {
        model.getHospitals();
        model.getFamilyFiles();
      },
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        imagesInfo: imagesInfo,
        appBarTitle: TranslationBase.of(context).advancePayment,
        description: TranslationBase.of(context).infoAdvancePayment,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        backgroundColor: CustomColors.appBackgroudGreyColor,
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(21),
                physics: BouncingScrollPhysics(),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      TranslationBase.of(context).advancePaymentLabel,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.64,
                      ),
                    ),
                    SizedBox(height: 12),
                    InkWell(
                      onTap: () {
                        List<RadioSelectionDialogModel> list = [
                          RadioSelectionDialogModel(TranslationBase.of(context).myAccount, 0),
                          RadioSelectionDialogModel(TranslationBase.of(context).myFamilyFiles, 1),
                          RadioSelectionDialogModel(TranslationBase.of(context).otherAccount, 2),
                        ];
                        showDialog(
                          context: context,
                          builder: (cxt) => RadioSelectionDialog(
                            listData: list,
                            selectedIndex:
                                beneficiaryType == BeneficiaryType.MyAccount ? 0 : (beneficiaryType == BeneficiaryType.MyFamilyFiles ? 1 : (beneficiaryType == BeneficiaryType.OtherAccount ? 2 : -1)),
                            onValueSelected: (index) {
                              var type;
                              if (index == 0) {
                                type = BeneficiaryType.MyAccount;
                              } else if (index == 1) {
                                type = BeneficiaryType.MyFamilyFiles;
                              } else {
                                type = BeneficiaryType.OtherAccount;
                              }

                              setState(() {
                                if (type == BeneficiaryType.MyAccount) {
                                  _fileTextController.text = model.user.patientID.toString();
                                  advanceModel.depositorName = model.user.firstName + " " + model.user.lastName;
                                } else
                                  _fileTextController.text = "";

                                beneficiaryType = type;
                              });
                            },
                          ),
                        );
                      },
                      child: Container(
                        padding: EdgeInsets.all(8),
                        width: double.infinity,
                        height: 65,
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: Colors.white),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              getBeneficiaryType(),
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.46,
                              ),
                            ),
                            Icon(Icons.arrow_drop_down)
                          ],
                        ),
                      ),
                    ),
                    if (beneficiaryType == BeneficiaryType.MyFamilyFiles) SizedBox(height: 12),
                    if (beneficiaryType == BeneficiaryType.MyFamilyFiles)
                      InkWell(
                        onTap: () {
                          GifLoaderDialogUtils.showMyDialog(context);
                          model.getFamilyFiles().then((value) {
                            GifLoaderDialogUtils.hideDialog(context);
                            confirmSelectFamilyDialog(model.getAllSharedRecordsByStatusResponse.getAllSharedRecordsByStatusList);
                          });
                        },
                        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: [
                              Text(
                                getFamilyMembersName(),
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: -0.46,
                                ),
                              ),
                              Icon(Icons.arrow_drop_down),
                            ],
                          ),
                        ),
                      ),
                    SizedBox(height: 12),
                    NewTextFields(
                      hintText: TranslationBase.of(context).fileNumber,
                      controller: _fileTextController,
                      readOnly: beneficiaryType == BeneficiaryType.OtherAccount ? false : true,
                    ),
                    if (beneficiaryType == BeneficiaryType.OtherAccount) SizedBox(height: 12),
                    if (beneficiaryType == BeneficiaryType.OtherAccount)
                      InkWell(
                        onTap: () {
                          if (_fileTextController.text.isNotEmpty) {
                            GifLoaderDialogUtils.showMyDialog(context);
                            model.getPatientInfoByPatientID(id: _fileTextController.text).then((value) {
                              GifLoaderDialogUtils.hideDialog(context);
                              confirmSelectPatientDialog(model.patientInfoList);
                            });
                          } else
                            AppToast.showErrorToast(message: 'Please Enter The File Number');
                        },
                        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: [
                              Text(
                                getPatientName(),
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  letterSpacing: -0.46,
                                ),
                              ),
                              Icon(Icons.arrow_drop_down),
                            ],
                          ),
                        ),
                      ),
                    SizedBox(height: 12),
                    InkWell(
                      onTap: () => confirmSelectHospitalDialog(model.hospitals),
                      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: [
                            Text(
                              getHospitalName(),
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.46,
                              ),
                            ),
                            Icon(Icons.arrow_drop_down),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 12),
                    NewTextFields(
                      hintText: TranslationBase.of(context).amount,
                      keyboardType: TextInputType.numberWithOptions(signed: false, decimal: true),
                      onChanged: (value) {
                        setState(() {
                          amount = value;
                        });
                      },
                    ),
                    SizedBox(height: 12),
                    if (model.user != null)
                      NewTextFields(
                        hintText: TranslationBase.of(context).depositorEmail,
                        initialValue: model.user.emailAddress,
                        onChanged: (value) {
                          email = value;
                        },
                      ),
                    SizedBox(height: 12),
                    NewTextFields(
                      hintText: TranslationBase.of(context).notes,
                      controller: _notesTextController,
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.15,
                    )
                  ],
                ),
              ),
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: 16, bottom: 16, right: 21, left: 21),
              child: DefaultButton(
                TranslationBase.of(context).submit,
                (amount.isEmpty || _fileTextController.text.isEmpty || _selectedHospital == null)
                    ? null
                    : () {
                        var mobileNum;
                        var patientName;

                        if (beneficiaryType == BeneficiaryType.MyFamilyFiles) {
                          mobileNum = selectedPatientFamily.mobileNumber;
                          patientName = selectedPatientFamily.patientName;
                        }

                        if (beneficiaryType == BeneficiaryType.MyAccount) {
                          mobileNum = model.user.mobileNumber;
                          patientName = model.user.firstName;
                        }

                        if (beneficiaryType == BeneficiaryType.OtherAccount) {
                          mobileNum = _selectedPatientInfo.mobileNumber;
                          patientName = _selectedPatientInfo.fullName;
                        }

                        advanceModel.fileNumber = _fileTextController.text;
                        advanceModel.hospitalsModel = _selectedHospital;
                        advanceModel.note = _notesTextController.text;
                        advanceModel.email = email ?? model.user.emailAddress;
                        advanceModel.amount = amount;
                        advanceModel.mobileNumber = mobileNum;
                        advanceModel.patientName = patientName;
                        GifLoaderDialogUtils.showMyDialog(context);


                        model.getPatientInfoByPatientIDAndMobileNumber(advanceModel).then((value) {
                          GifLoaderDialogUtils.hideDialog(context);
                          if (model.state != ViewState.Error && model.state != ViewState.ErrorLocal) {
                            Utils.hideKeyboard(context);
                            Navigator.push(
                              context,
                              FadePage(
                                page: PaymentMethod(
                                    onSelectedMethod: (String metohd, [String selectedInstallmentPlan]) {
                                      setState(() {});
                                    },
                                    isShowInstallments: false, isFromAdvancePayment: true),
                              ),
                            ).then(
                              (value) {
                                Navigator.push(
                                  context,
                                  FadePage(
                                    page: ConfirmPaymentPage(
                                      advanceModel: advanceModel,
                                      selectedPaymentMethod: value[0],
                                      patientInfoAndMobileNumber: model.patientInfoAndMobileNumber,
                                      authenticatedUser: authUser,
                                      installmentPlan: value[1],
                                    ),
                                  ),
                                );
                                projectViewModel.analytics.advancePayments.payment_method(method: value[0].toString().toLowerCase(), type: 'wallet');
                              },
                            );
                          }
                        });
                        projectViewModel.analytics.advancePayments.wallet_payment_details();
                      },
                color: Color(0xffD02127),
                textColor: Colors.white,
                disabledColor: Color(0xffEAEAEA),
              ),
            ),
          ],
        ),
      ),
    );
  }

  int _selectedHospitalIndex = -1;

  void confirmSelectHospitalDialog(List<HospitalsModel> hospitals) {
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < hospitals.length; i++) RadioSelectionDialogModel(hospitals[i].name + ' ${hospitals[i].distanceInKilometers} ' + TranslationBase.of(context).km, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        selectedIndex: _selectedHospitalIndex,
        isScrollable: true,
        onValueSelected: (index) {
          _selectedHospitalIndex = index;
          _selectedHospital = hospitals[index];
          setState(() {});
        },
      ),
    );
  }

  int _selectedPatientIndex = -1;

  void confirmSelectPatientDialog(List<PatientInfo> patientInfoList) {
    List<RadioSelectionDialogModel> list = [
      for (int i = 0; i < patientInfoList.length; i++) RadioSelectionDialogModel(patientInfoList[i].fullName, i),
    ];
    showDialog(
      context: context,
      builder: (cxt) => RadioSelectionDialog(
        listData: list,
        isScrollable: true,
        selectedIndex: _selectedPatientIndex,
        onValueSelected: (index) {
          _selectedPatientIndex = index;
          _selectedPatientInfo = patientInfoList[index];
          advanceModel.depositorName = _selectedPatientInfo.fullName;
          setState(() {});
        },
      ),
    );
  }

  int _selectedFamilyMemberIndex = -1;

  void confirmSelectFamilyDialog(List<GetAllSharedRecordsByStatusList> getAllSharedRecordsByStatusList) {
    if (getAllSharedRecordsByStatusList.isNotEmpty) {
      List<RadioSelectionDialogModel> list = [
        for (int i = 0; i < getAllSharedRecordsByStatusList.length; i++)
          if (getAllSharedRecordsByStatusList[i].status == 3) RadioSelectionDialogModel(getAllSharedRecordsByStatusList[i].patientName, i),
      ];
      showDialog(
        context: context,
        builder: (cxt) => RadioSelectionDialog(
          listData: list,
          isScrollable: true,
          selectedIndex: _selectedFamilyMemberIndex,
          onValueSelected: (index) {
            _selectedFamilyMemberIndex = index;
            selectedPatientFamily = getAllSharedRecordsByStatusList[index];
            _fileTextController.text = selectedPatientFamily.responseID.toString();
            setState(() {});
          },
        ),
      );
    }
  }

  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 getHospitalName() {
    if (_selectedHospital != null)
      return _selectedHospital.name;
    else
      return 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;
  }
}
