import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/blood_pressure_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/medical/balance/new_text_Field.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/radio_selection_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:provider/provider.dart';

class AddBloodPressurePage extends StatefulWidget {
  final DateTime bloodSugarDate;
  final String measureTimeSelectedType;
  final bool isUpdate;
  final int lineItemNo;
  final int measuredArm;
  final String bloodSystolicValue;
  final String bloodDiastolicValue;
  final BloodPressureViewMode model;

  const AddBloodPressurePage(
      {Key key, this.bloodSugarDate, this.measureTimeSelectedType, this.isUpdate = false, this.lineItemNo, this.measuredArm, this.model, this.bloodSystolicValue, this.bloodDiastolicValue})
      : super(key: key);

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

class _AddBloodPressurePageState extends State<AddBloodPressurePage> {
  TextEditingController _bloodSystolicValueController = TextEditingController();
  TextEditingController _bloodDiastolicValueController = TextEditingController();
  DateTime bloodSugarDate = DateTime.now();
  DateTime timeSugarDate = DateTime.now();
  int measuredArm = 0;
  bool isButtonDisabled = true;
  final List<String> measureTimeEnList = ['Left Arm', 'Right Arm'];
  final List<String> measureTimeArList = ['الذراع الأيسر', 'الذراع الأيمن'];
  String measureTimeSelectedType = 'Left Arm';

  @override
  void initState() {
    super.initState();
    if (widget.isUpdate) {
      bloodSugarDate = widget.bloodSugarDate;
      bloodSugarDate = widget.bloodSugarDate;
      measureTimeSelectedType = widget.measureTimeSelectedType;
      measuredArm = widget.measuredArm;
      if (measuredArm > 1) measuredArm = measuredArm - 1;

      _bloodSystolicValueController.text = widget.bloodSystolicValue;
      _bloodDiastolicValueController.text = widget.bloodDiastolicValue;
      validateForm();
    }
  }

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

    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: widget.isUpdate ? TranslationBase.of(context).update : TranslationBase.of(context).add,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      body: Column(
        children: [
          Expanded(
            child: ListView(
              physics: BouncingScrollPhysics(),
              padding: EdgeInsets.all(21),
              children: [
                NewTextFields(
                  hintText: TranslationBase.of(context).systolicAdd,
                  controller: _bloodSystolicValueController,
                  keyboardType: TextInputType.number,
                  maxLength: 3,
                  onChanged: (value) => validateForm(),
                  fontWeight: FontWeight.normal,
                  fontSize: 14,
                ),
                SizedBox(height: 12),
                NewTextFields(
                  hintText: TranslationBase.of(context).diastolicAdd,
                  controller: _bloodDiastolicValueController,
                  keyboardType: TextInputType.number,
                  maxLength: 3,
                  onChanged: (value) => validateForm(),
                  fontWeight: FontWeight.normal,
                  fontSize: 14,
                ),
                SizedBox(height: 12),
                InkWell(
                  onTap: () {
                    List<RadioSelectionDialogModel> list = [
                      RadioSelectionDialogModel(projectViewModel.isArabic ? measureTimeArList[0] : measureTimeEnList[0], 0),
                      RadioSelectionDialogModel(projectViewModel.isArabic ? measureTimeArList[1] : measureTimeEnList[1], 1),
                    ];

                    showDialog(
                      context: context,
                      builder: (cxt) => RadioSelectionDialog(
                        listData: list,
                        selectedIndex: measuredArm,
                        onValueSelected: (index) {
                          measuredArm = index;
                          measureTimeSelectedType = list[index].title;
                          setState(() {});
                          validateForm();
                        },
                      ),
                    );
                  },
                  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(projectViewModel.isArabic ? measureTimeArList[measuredArm] : measureTimeEnList[measuredArm]),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colors.grey,
                        )
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 12),
                InkWell(
                  onTap: () {
                    DatePicker.showDatePicker(context, showTitleActions: true, minTime: DateTime(DateTime.now().year - 1, 1, 1), maxTime: DateTime.now(), onConfirm: (date) {
                      setState(
                        () {
                          bloodSugarDate = date;
                        },
                      );
                    }, currentTime: bloodSugarDate, locale: projectViewModel.localeType);
                  },
                  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(TranslationBase.of(context).date),
                        Texts(getDate()),
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 12),
                InkWell(
                  onTap: () {
                    DatePicker.showTimePicker(context, showTitleActions: true, onConfirm: (date) {
                      setState(
                        () {
                          timeSugarDate = date;
                        },
                      );
                    }, currentTime: timeSugarDate, locale: projectViewModel.localeType);
                  },
                  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(TranslationBase.of(context).time), Texts(getTime())],
                    ),
                  ),
                ),
                widget.isUpdate
                    ? Container(
                        padding: EdgeInsets.all(10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            InkWell(
                                child: Texts(
                                  TranslationBase.of(context).delete,
                                  decoration: TextDecoration.underline,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.red[900],
                                ),
                                onTap: () {
                                  ConfirmDialog dialog = new ConfirmDialog(
                                      context: context,
                                      confirmMessage: TranslationBase.of(context).removeMeasure,
                                      okText: TranslationBase.of(context).ok,
                                      cancelText: TranslationBase.of(context).cancel,
                                      okFunction: () async {
                                        ConfirmDialog.closeAlertDialog(context);

                                        GifLoaderDialogUtils.showMyDialog(context);
                                        widget.model.deactivateDiabeticStatus(lineItemNo: widget.lineItemNo).then((value) {
                                          GifLoaderDialogUtils.hideDialog(context);
                                          if (widget.model.state == ViewState.ErrorLocal)
                                            AppToast.showErrorToast(message: widget.model.error);
                                          else
                                            Navigator.pop(context);
                                        }).catchError((e) {
                                          GifLoaderDialogUtils.hideDialog(context);
                                          AppToast.showErrorToast(message: widget.model.error);
                                        });
                                      },
                                      cancelFunction: () => {});
                                  dialog.showAlertDialog(context);
                                })
                          ],
                        ))
                    : Container()
              ],
            ),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 16, bottom: 16, right: 21, left: 21),
            child: DefaultButton(
              TranslationBase.of(context).save,
              isButtonDisabled
                  ? null
                  : () async {
                      if (_bloodSystolicValueController.text.isNotEmpty && _bloodDiastolicValueController.text.isNotEmpty) {
                        GifLoaderDialogUtils.showMyDialog(context);
                        widget.model
                            .addORUpdateDiabtecResult(
                                isUpdate: widget.isUpdate,
                                bloodPressureDate: '${bloodSugarDate.year}-${bloodSugarDate.month}-${bloodSugarDate.day} ${timeSugarDate.hour}:${timeSugarDate.minute}:00',
                                diastolicPressure: _bloodDiastolicValueController.text.toString(),
                                systolicePressure: _bloodSystolicValueController.text.toString(),
                                measuredArm: (measuredArm),
                                lineItemNo: widget.lineItemNo)
                            .then((value) {
                          GifLoaderDialogUtils.hideDialog(context);
                          if (widget.model.state == ViewState.BusyLocal)
                            AppToast.showErrorToast(message: widget.model.error);
                          else
                            Navigator.pop(context);
                          ;
                        }).catchError((e) {
                          GifLoaderDialogUtils.hideDialog(context);
                          AppToast.showErrorToast(message: widget.model.error);
                        });
                      }
                    },
              disabledColor: Colors.grey,
            ),
          )
        ],
      ),
    );
  }

  String getDate() {
    return "${DateUtil.getMonth(bloodSugarDate.month)} ${bloodSugarDate.day}, ${bloodSugarDate.year}";
  }

  String getTime() {
    return " ${timeSugarDate.hour}:${timeSugarDate.minute}";
  }

  void validateForm() {
    print("_bloodSystolicValueController " + _bloodSystolicValueController.text.length.toString());
    if (_bloodSystolicValueController.text.length > 0 && _bloodDiastolicValueController.text.length > 0) {
      setState(() {
        isButtonDisabled = false;
      });
    } else {
      setState(() {
        isButtonDisabled = true;
      });
    }
    // if(measureTimeSelectedType == 'Left Arm'){
    //   setState(() {
    //     isButtonDisabled = false;
    //   });
    // }else if(_bloodSystolicValueController.text.length < 0){
    //   setState(() {
    //     isButtonDisabled = false;
    //   });
    // }else if(_bloodDiastolicValueController.text.length < 0){
    //   setState(() {
    //     isButtonDisabled = false;
    //   });
    // }else{
    //   setState(() {
    //     isButtonDisabled = true;
    //   });
    // }
  }
}
