import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/weight_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/ConfirmWithMessageDialog.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 AddWeightPage extends StatefulWidget {
  final WeightPressureViewModel model;
  final bool isUpdate;
  final DateTime dayWeightDate;
  final int lineItemNo;
  final String weightValue;
  final String measureTimeSelectedType;
  final int weightUnit;

  AddWeightPage({Key key, this.model, this.isUpdate = false, this.dayWeightDate, this.lineItemNo, this.weightValue, this.measureTimeSelectedType, this.weightUnit}) : super(key: key);

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

class _AddWeightPageState extends State<AddWeightPage> {
  TextEditingController _weightValueController = TextEditingController();
  DateTime dayWeightDate = DateTime.now();
  DateTime timeWeightDate = DateTime.now();
  int weightUnit = 0;
  final List<String> measureUnitEnList = [
    'Pound',
    'Kg',
  ];
  final List<String> measureUnitArList = [
    "باوند",
    "كيلو جرام",
  ];
  String measureTimeSelectedType;
  bool isButtonDisabled = true;

  @override
  void initState() {
    super.initState();
    if (widget.isUpdate) {
      dayWeightDate = widget.dayWeightDate;
      timeWeightDate = widget.dayWeightDate;
      measureTimeSelectedType = widget.measureTimeSelectedType;
      weightUnit = widget.weightUnit;
      _weightValueController.text = widget.weightValue;
      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(
              padding: EdgeInsets.all(21),
              physics: BouncingScrollPhysics(),
              children: [
                NewTextFields(
                  hintText: TranslationBase.of(context).weightAdd,
                  controller: _weightValueController,
                  keyboardType: TextInputType.number,
                  onChanged: (value) => validateForm(),
                  fontWeight: FontWeight.normal,
                  fontSize: 14,
                ),
                SizedBox(height: 12),
                InkWell(
                  onTap: () {
                    List<RadioSelectionDialogModel> list = [
                      RadioSelectionDialogModel(projectViewModel.isArabic ? measureUnitArList[0] : measureUnitEnList[0], 0),
                      RadioSelectionDialogModel(projectViewModel.isArabic ? measureUnitArList[1] : measureUnitEnList[1], 1),
                    ];

                    showDialog(
                      context: context,
                      builder: (cxt) => RadioSelectionDialog(
                        listData: list,
                        selectedIndex: weightUnit,
                        onValueSelected: (index) {
                          weightUnit = 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(measureTimeSelectedType ?? TranslationBase.of(context).other),
                        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(() {
                          dayWeightDate = date;
                        });
                      },
                      currentTime: dayWeightDate,
                      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(() {
                          timeWeightDate = date;
                        });
                      },
                      currentTime: timeWeightDate,
                      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: () {
                                  showDialog(
                                    context: context,
                                    builder: (cxt) => ConfirmWithMessageDialog(
                                      message: TranslationBase.of(context).removeMeasure,
                                      onTap: () async {
                                        GifLoaderDialogUtils.showMyDialog(context);
                                        widget.model.deleteWeightResult(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);
                                        });
                                      },
                                    ),
                                  );
                                  return;
                                })
                          ],
                        ),
                      )
                    : Container()
              ],
            ),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 16, bottom: 16, right: 21, left: 21),
            child: DefaultButton(
              TranslationBase.of(context).save.toUpperCase(),
              isButtonDisabled
                  ? null
                  : () async {
                      if (_weightValueController.text.isNotEmpty) {
                        GifLoaderDialogUtils.showMyDialog(context);
                        if (widget.isUpdate) {
                          widget.model
                              .updateWeightResult(
                                  weightDate: '${dayWeightDate.year}-${dayWeightDate.month}-${dayWeightDate.day} ${timeWeightDate.hour}:${timeWeightDate.minute}:00',
                                  weightMeasured: _weightValueController.text.toString(),
                                  weightUnit: weightUnit,
                                  lineItemNo: widget.lineItemNo)
                              .then((value) {
                            GifLoaderDialogUtils.hideDialog(context);
                            if (widget.model.state == ViewState.Error)
                              AppToast.showErrorToast(message: widget.model.error);
                            else
                              Navigator.pop(context);
                          });
                        } else
                          widget.model
                              .addWeightResult(
                            weightDate: '${dayWeightDate.year}-${dayWeightDate.month}-${dayWeightDate.day} ${timeWeightDate.hour}:${timeWeightDate.minute}:00',
                            weightMeasured: _weightValueController.text.toString(),
                            weightUnit: weightUnit,
                          )
                              .then((value) {
                            GifLoaderDialogUtils.hideDialog(context);
                            if (widget.model.state == ViewState.Error)
                              AppToast.showErrorToast(message: widget.model.error);
                            else
                              Navigator.pop(context);
                          });
                      }
                    },
              disabledColor: Colors.grey,
            ),
          )
        ],
      ),
    );
  }

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

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

  void validateForm() {
    if (_weightValueController.text.length > 0 && measureTimeSelectedType != null) {
      setState(() {
        isButtonDisabled = false;
      });
    } else {
      setState(() {
        isButtonDisabled = true;
      });
    }
  }
}
