import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/blood_sugar_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 AddBloodSugarPage extends StatefulWidget {
  final DateTime bloodSugarDate;
  final String measureUnitSelectedType;
  final bool isUpdate;
  final String measuredTime;
  final String bloodSugarValue;
  final int lineItemNo;
  final BloodSugarViewMode bloodSugarViewMode;

  AddBloodSugarPage(
      {Key key,
        this.bloodSugarDate,
        this.measureUnitSelectedType,
        this.isUpdate = false,
        this.measuredTime,
        this.bloodSugarValue,
        this.lineItemNo,
        this.bloodSugarViewMode})
      : super(key: key);

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

class _AddBloodSugarPageState extends State<AddBloodSugarPage> {
  TextEditingController _bloodSugarValueController = TextEditingController();
  DateTime bloodSugarDate = DateTime.now();
  DateTime timeSugarDate = DateTime.now();
  String measureUnitSelectedType = 'mg/dlt';
  int measuredTime = 1;
  bool isButtonDisabled = false;
  final List<String> measureUnitList = ['mg/dlt', 'mol/L'];
  final List<String> measureTimeEnList = [
    'Before Breakfast',
    'After Breakfast',
    'Before Lunch',
    'After Lunch',
    'Before Dinner',
    'After Dinner',
    'Before Sleep',
    'After Sleep',
    'Fasting',
    'Other',
  ];
  final List<String> measureTimeArList = [
    "قبل الإفطار",
    "بعد الإفطار",
    "بعد الغداء",
    "بعد الغداء",
    "قبل العشاء",
    "بعد العشاء",
    "قبل النوم",
    "بعد النوم",
    "صائم",
    "آخر",
  ];
  String measureTimeSelectedType;

  @override
  void initState() {
    super.initState();
    if (widget.isUpdate) {
      bloodSugarDate = widget.bloodSugarDate;
      timeSugarDate = widget.bloodSugarDate;
      measureUnitSelectedType = widget.measureUnitSelectedType;
      if (measureTimeEnList.contains(widget.measuredTime))
        measuredTime = measureTimeEnList.indexOf(widget.measuredTime);
      else if (measureTimeArList.contains(widget.measuredTime))
        measuredTime = measureTimeArList.indexOf(widget.measuredTime);
      _bloodSugarValueController.text = widget.bloodSugarValue;
      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.bloodSugarViewMode
                    .deactivateDiabeticStatus(
                    lineItemNo: widget.lineItemNo)
                    .then((value) {
                  GifLoaderDialogUtils.hideDialog(context);
                  if (widget.bloodSugarViewMode.state ==
                      ViewState.ErrorLocal)
                    AppToast.showErrorToast(
                        message: widget.bloodSugarViewMode.error);
                  else
                    Navigator.pop(context);
                }).catchError((e) {
                  GifLoaderDialogUtils.hideDialog(context);
                  AppToast.showErrorToast(
                      message: widget.bloodSugarViewMode.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).sugarAdd,
                controller: _bloodSugarValueController,
                keyboardType: TextInputType.number,
                onChanged: (value) => validateForm(),
              ),
              SizedBox(
                height: 8,
              ),
              InkWell(
                onTap: () {
                  confirmSelectMeasureUnitDialog();
                },
                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(measureUnitSelectedType),
                      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())
                    ],
                  ),
                ),
              ),
              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 ??
                          TranslationBase.of(context).other),
                      Icon(
                        Icons.arrow_drop_down,
                        color: Colors.grey,
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        color: Colors.transparent,
        width: double.infinity,
        height: MediaQuery.of(context).size.height * 0.10,
        child: Column(
          children: [
            FractionallySizedBox(
              widthFactor: 0.9,
              child: SecondaryButton(
                  label: TranslationBase.of(context).save.toUpperCase(),
                  textColor: Colors.white,
                  color: isButtonDisabled ? Colors.grey[900] : Colors.grey,
                  onTap: () async {
                    if (_bloodSugarValueController.text.isNotEmpty) {
                      if (widget.isUpdate) {
                        GifLoaderDialogUtils.showMyDialog(context);
                        await widget.bloodSugarViewMode
                            .updateDiabtecResult(
                            month: bloodSugarDate,
                            hour: timeSugarDate,
                            diabtecUnit: measureUnitSelectedType,
                            measuredTime: measuredTime,
                            lineItemNo: widget.lineItemNo,
                            bloodSugerResult:
                            _bloodSugarValueController.text.toString());

                          GifLoaderDialogUtils.hideDialog(context);
                          if (widget.bloodSugarViewMode.state ==
                              ViewState.ErrorLocal)
                            AppToast.showErrorToast(
                                message: widget.bloodSugarViewMode.error);
                          else
                            Navigator.pop(context);

                      } else {
                        GifLoaderDialogUtils.showMyDialog(context);
                        await widget.bloodSugarViewMode
                            .addDiabtecResult(
                          diabtecUnit: measureUnitSelectedType,
                          measuredTime: measuredTime,
                          bloodSugerResult:
                          _bloodSugarValueController.text.toString(),
                          bloodSugerDateChart:
                          '${bloodSugarDate.year}-${bloodSugarDate.month}-${bloodSugarDate.day} ${timeSugarDate.hour}:${timeSugarDate.minute}:00',
                        );

                          GifLoaderDialogUtils.hideDialog(context);
                          if (widget.bloodSugarViewMode.state == ViewState.Error)
                            AppToast.showErrorToast(
                                message: widget.bloodSugarViewMode.error);
                          else
                            Navigator.pop(context);

                      }

                    }
                  }),
            ),
          ],
        ),
      ),
    );
  }

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

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

  void confirmSelectMeasureUnitDialog() {
    showDialog(
      context: context,
      child: RadioStringDialog(
        radioList: measureUnitList,
        title: TranslationBase.of(context).measureUnit,
        selectedValue: measureUnitSelectedType,
        onValueSelected: (value) {
          setState(() {
            measureUnitSelectedType = value;
          });
        },
      ),
    );
  }

  void confirmSelectMeasureTimeDialog(List<String> list) {
    showDialog(
      context: context,
      child: RadioStringDialog(
        radioList: list,
        title: TranslationBase.of(context).measureTime,
        selectedValue: measureTimeSelectedType,
        onValueSelected: (value) {
          setState(() {
            measureTimeSelectedType = value;
            measuredTime = list.indexOf(value);
          });
        },
      ),
    );
  }

  void validateForm() {
    if (_bloodSugarValueController.text.length > 0) {
      setState(() {
        isButtonDisabled = true;
      });
    } else {
      setState(() {
        isButtonDisabled = false;
      });
    }
  }
}
