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/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/RadioStringDialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_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 String bloodSystolicValue;
  final String bloodDiastolicValue;
  final BloodPressureViewMode model;

  const AddBloodPressurePage(
      {Key key,
      this.bloodSugarDate,
      this.measureTimeSelectedType,
      this.isUpdate = false,
      this.lineItemNo,
      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 = 1;
  bool isButtonDisabled = false;
  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;
      if (measureTimeEnList.contains(widget.measureTimeSelectedType))
        measuredArm = measureTimeEnList.indexOf(widget.measureTimeSelectedType);
      else if (measureTimeArList.contains(widget.measureTimeSelectedType))
        measuredArm = measureTimeArList.indexOf(widget.measureTimeSelectedType);
      _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,
      appBarIcons: widget.isUpdate
          ? [
              IconButton(
                icon: Icon(Icons.delete),
                color: Colors.white,
                onPressed: () {
                  ConfirmDialog dialog = new ConfirmDialog(
                      context: context,
                      confirmMessage: 'Remove this measure',
                      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);
                },
              )
            ]
          : null,
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Container(
          margin: EdgeInsets.all(15),
          child: Column(
            children: [
              SizedBox(
                height: 15,
              ),
              NewTextFields(
                hintText: TranslationBase.of(context).systolicAdd,
                controller: _bloodSystolicValueController,
                keyboardType: TextInputType.number,
                maxLength: 3,
                onChanged: (value) => validateForm(),
              ),
              SizedBox(
                height: 8,
              ),
              NewTextFields(
                hintText: TranslationBase.of(context).diastolicAdd,
                controller: _bloodDiastolicValueController,
                keyboardType: TextInputType.number,
                maxLength: 3,
                onChanged: (value) => validateForm(),
              ),
              SizedBox(
                height: 8,
              ),
              InkWell(
                onTap: () {
                  confirmSelectMeasureTimeDialog(projectViewModel.isArabic
                      ? measureTimeArList
                      : measureTimeEnList);
                },
                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(measureTimeSelectedType),
                      Icon(
                        Icons.arrow_drop_down,
                        color: Colors.grey,
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 8,
              ),
              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: 8,
              ),
              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())
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        color: Colors.transparent,
        width: double.infinity,
        height: MediaQuery.of(context).size.height * 0.10,
        child: FractionallySizedBox(
          widthFactor: 0.9,
          child: Column(
            children: [
              Container(
                height: 50,
                child: SecondaryButton(
                    loading: widget.model.state == ViewState.BusyLocal,
                    label: TranslationBase.of(context).save.toUpperCase(),
                    textColor: Colors.white,
                    color: isButtonDisabled ? Colors.grey[900] : Colors.grey,
                    onTap: () 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,
                        )
                            .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);
                        });
                      }
                    }),
              ),
            ],
          ),
        ),
      ),
    );
  }

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

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

  void confirmSelectMeasureTimeDialog(List<String> list) {
    showDialog(
      context: context,
      child: RadioStringDialog(
        radioList: list,
        title: 'Select the Arm',
        selectedValue: measureTimeSelectedType,
        onValueSelected: (value) {
          setState(() {
            measureTimeSelectedType = value;
            measuredArm = list.indexOf(value);
            validateForm();
          });
        },
      ),
    );
  }

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