import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/H2O/user_detail_model.dart';
import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/H2O_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/H2O_view_model.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/BranchView.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.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/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:manage_calendar_events/manage_calendar_events.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'Dialog/setting_page_radio_button_list_dialog.dart';

class H2oSetting extends StatefulWidget {
  final UserDetailModel userDetailModel;
  final H2OViewModel viewModel;
  H2oSetting({Key key, this.userDetailModel, this.viewModel}) : super(key: key);

  @override
  _H2oSettingState createState() {
    return _H2oSettingState();
  }
}

class _H2oSettingState extends State<H2oSetting> {
  TextEditingController _nameController = TextEditingController();
  TextEditingController _heightController = TextEditingController();
  TextEditingController _weightController = TextEditingController();
  bool _isUnitML = true;
  bool _isGenderMale = false;
  bool _isHeightCM = false;
  bool _isWeightKG = false;
  double _heightValue = 1;
  double _weightValue = 1;

  List<String> _activityLevelListEng = [];
  List<String> _remindedTimeListEng = [];
  int _selectedActiveLevel = 1;
  int _selectedRemindedTime = 0;
  DateTime _dobDate = DateTime.now();
  DateTime _tempDate = DateTime.now();

  UserDetailModel _userDetailModel;

  @override
  void initState() {
    super.initState();
    _userDetailModel = widget.userDetailModel;
    _heightValue = _userDetailModel?.height ?? 100;
    _weightValue = _userDetailModel?.weight ?? 50;
    _heightController.text = _heightValue.toStringAsFixed(0);
    _weightController.text = _weightValue.toStringAsFixed(0);
    _nameController.text = _userDetailModel.firstName;
    _isWeightKG = _userDetailModel?.isWeightInKG ?? true;
    _isHeightCM = _userDetailModel?.isHeightInCM ?? true;
    _isGenderMale = (_userDetailModel?.gender ?? "M") == "M" ? true : false;
    _dobDate = DateUtil.convertStringToDate(_userDetailModel.dOB);
    _selectedActiveLevel = _userDetailModel.activityID ?? 1;
    readPrefs();
  }

  SharedPreferences prefs;
  void readPrefs() async {
    prefs = await SharedPreferences.getInstance();
    _isUnitML = (prefs.getString(H2O_UNIT) ?? "ml") == "ml" ? true : false;
    _selectedRemindedTime = prefs.getInt(H2O_REMINDER) ?? 0;
    setState(() {});
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();

    _activityLevelListEng = [TranslationBase.of(context).notActive, TranslationBase.of(context).lightActive, TranslationBase.of(context).modActive, TranslationBase.of(context).active];

    _remindedTimeListEng = ["1 ${TranslationBase.of(context).time}", "2 ${TranslationBase.of(context).times}", "3 ${TranslationBase.of(context).times}", "4 ${TranslationBase.of(context).times}"];
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).h2o,
      showHomeAppBarIcon: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.fromLTRB(8, 8, 8, 80),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _nameController,
              decoration: InputDecoration(
                labelText: TranslationBase.of(context).enterNameHere,
                labelStyle: TextStyle(color: Colors.black87),
                fillColor: Colors.white,
                filled: true,
                border: UnderlineInputBorder(
                  borderSide: BorderSide(
                    width: 0,
                    style: BorderStyle.none,
                  ),
                  borderRadius: BorderRadius.circular(6.0),
                ),
              ),
            ),
            SizedBox(height: 8),
            Text(TranslationBase.of(context).preferredunit),
            SizedBox(height: 8),
            _commonButtonsRow(TranslationBase.of(context).ml, TranslationBase.of(context).l, _isUnitML, (value) {
              if (_isUnitML != value) {
                setState(() {
                  _isUnitML = value;
                });
              }
            }),
            Padding(
              padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: Divider(height: 1.5, color: Colors.black54),
            ),
            Text(TranslationBase.of(context).gender),
            SizedBox(height: 8),
            _commonButtonsRow(TranslationBase.of(context).male, TranslationBase.of(context).female, _isGenderMale, (value) {
              if (_isGenderMale != value) {
                setState(() {
                  _isGenderMale = value;
                });
              }
            }),
            Padding(
              padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: Divider(height: 1.5, color: Colors.black54),
            ),
            Text(TranslationBase.of(context).height),
            _commonSlidersRow(_heightController, 1, 270, _heightValue, (text) {
              _heightController.text = text;
            }, (value) {
              setState(() {
                _heightValue = value;
              });
            }),
            SizedBox(height: 8),
            Text(TranslationBase.of(context).heightUnit),
            SizedBox(height: 8),
            _commonButtonsRow(TranslationBase.of(context).cm, TranslationBase.of(context).ft, _isHeightCM, (value) {
              if (_isHeightCM != value) {
                setState(() {
                  _isHeightCM = value;
                });
              }
            }),
            SizedBox(height: 8),
            _commonSlidersRow(_weightController, 1, 250, _weightValue, (text) {
              _weightController.text = text;
            }, (value) {
              setState(() {
                _weightValue = value;
              });
            }),
            SizedBox(height: 8),
            Text(TranslationBase.of(context).weightUnit),
            SizedBox(height: 8),
            _commonButtonsRow(TranslationBase.of(context).kg, TranslationBase.of(context).lb, _isWeightKG, (value) {
              if (_isWeightKG != value) {
                setState(() {
                  _isWeightKG = value;
                });
              }
            }),
            Padding(
              padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
              child: Divider(height: 1.5, color: Colors.black54),
            ),
            Container(
              padding: EdgeInsets.all(8),
              width: MediaQuery.of(context).size.width,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: Colors.white),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("${TranslationBase.of(context).birth_date}:"),
                  SizedBox(height: 8),
                  InkWell(
                    onTap: () {
                      showModalBottomSheet(
                          context: context,
                          builder: (context) {
                            return Container(
                              height: 250,
                              padding: EdgeInsets.all(8),
                              child: Column(children: [
                                Container(
                                  height: 40,
                                  alignment: Alignment.centerRight,
                                  child: Row(mainAxisSize: MainAxisSize.min, children: [
                                    InkWell(
                                      onTap: () => Navigator.pop(context),
                                      child: Container(
                                        alignment: Alignment.center,
                                        padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                                        child: Text(TranslationBase.of(context).cancel),
                                      ),
                                    ),
                                    SizedBox(width: 8),
                                    InkWell(
                                      onTap: () {
                                        Navigator.pop(context);
                                        setState(() {
                                          _dobDate = _tempDate;
                                        });
                                      },
                                      child: Container(
                                        alignment: Alignment.center,
                                        padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                                        child: Text(TranslationBase.of(context).ok),
                                      ),
                                    )
                                  ]),
                                ),
                                Expanded(
                                  child: Container(
                                    width: MediaQuery.of(context).size.width,
                                    child: CupertinoDatePicker(
                                      initialDateTime: _dobDate,
                                      mode: CupertinoDatePickerMode.date,
                                      onDateTimeChanged: (_date) {
                                        _tempDate = _date;
                                      },
                                    ),
                                  ),
                                )
                              ]),
                            );
                          });
                    }, // implement cupertino dialog to select date
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [Text(DateUtil.getFormattedDate(_dobDate, "yyyy-MM-dd")), Icon(Icons.arrow_drop_down_outlined)]),
                  )
                ],
              ),
            ),
            SizedBox(height: 8),
            _commonDialogSelectorRow(TranslationBase.of(context).activityLevel, _activityLevelListEng[_selectedActiveLevel - 1], () {
              showDialog(
                context: context,
                child: CommonRadioButtonDialog(
                  list: _activityLevelListEng,
                  title: TranslationBase.of(context).activityLevel,
                  onSelect: (index) {
                    Navigator.pop(context);
                    setState(() {
                      _selectedActiveLevel = index + 1;
                    });
                  },
                  selectedIndex: _selectedActiveLevel - 1,
                ),
              );
            }),
            SizedBox(height: 8),
            _commonDialogSelectorRow(TranslationBase.of(context).reminderLabel, _remindedTimeListEng[_selectedRemindedTime], () {
              showDialog(
                context: context,
                child: CommonRadioButtonDialog(
                  list: _remindedTimeListEng,
                  onSelect: (index) {
                    Navigator.pop(context);
                    setState(() {
                      _selectedRemindedTime = index;
                    });
                  },
                  selectedIndex: _selectedRemindedTime,
                ),
              );
            }),
            SizedBox(height: 16),
            SizedBox(
              height: 50,
              width: MediaQuery.of(context).size.width,
              child: FlatButton(
                color: Theme.of(context).appBarTheme.color,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
                onPressed: _updateUserDetails,
                child: Text(
                  TranslationBase.of(context).save,
                  style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w600),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _commonButtonsRow(String rightText, String leftText, bool checkParam, Function(bool) callBack) {
    return Row(children: [
      Expanded(
        child: SizedBox(
          height: 40,
          child: RaisedButton(
            color: checkParam ? Theme.of(context).appBarTheme.color : Colors.white,
            child: Text(
              rightText,
              style: TextStyle(color: checkParam ? Colors.white : Theme.of(context).appBarTheme.color, fontWeight: FontWeight.w600),
            ),
            onPressed: () => callBack(true),
          ),
        ),
      ),
      SizedBox(width: 12),
      Expanded(
        child: SizedBox(
          height: 40,
          child: RaisedButton(
            color: !checkParam ? Theme.of(context).appBarTheme.color : Colors.white,
            child: Text(
              leftText,
              style: TextStyle(color: !checkParam ? Colors.white : Theme.of(context).appBarTheme.color, fontWeight: FontWeight.w600),
            ),
            onPressed: () => callBack(false),
          ),
        ),
      ),
    ]);
  }

  Widget _commonSlidersRow(_controller, double _minValue, double _maxValue, double _valueOrg, Function(String) onTextValueChange, Function(double) onValueChange) {
    return Container(
      margin: EdgeInsets.only(top: 6),
      padding: EdgeInsets.all(6),
      color: Colors.white,
      height: 50,
      child: Row(
        children: [
          SizedBox(
            width: 75,
            child: TextField(
              controller: _controller,
              textAlign: TextAlign.center,
              keyboardType: TextInputType.number,
              onChanged: (value) {
                double _value = double.parse(value);
                if (_value > _maxValue) {
                  onTextValueChange(_maxValue.toStringAsFixed(0));
                  onValueChange(_maxValue);
                  return;
                } else if (_value < _minValue) {
                  onTextValueChange(_minValue.toStringAsFixed(0));
                  onValueChange(_minValue);
                  return;
                } else if (_value >= _minValue && _value <= _maxValue) {
                  onValueChange(_value);
                  return;
                }
              },
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
              ],
              decoration: InputDecoration(
                contentPadding: EdgeInsets.only(left: 4, right: 4),
                fillColor: Colors.white,
                filled: true,
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    width: 1,
                    color: Colors.grey,
                    style: BorderStyle.solid,
                  ),
                  borderRadius: BorderRadius.circular(6.0),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    width: 1,
                    color: Colors.grey,
                    style: BorderStyle.solid,
                  ),
                  borderRadius: BorderRadius.circular(6.0),
                ),
              ),
            ),
          ),
          Expanded(
            flex: 6,
            child: Slider(
              min: _minValue,
              max: _maxValue,
              activeColor: Colors.redAccent,
              inactiveColor: Colors.redAccent.withOpacity(.3),
              value: _valueOrg,
              onChanged: (value) {
                onTextValueChange(value.toStringAsFixed(0));
                onValueChange(value);
              },
            ),
          )
        ],
      ),
    );
  }

  Widget _commonDialogSelectorRow(String title, String selectedText, VoidCallback onPressed) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
      Text(title),
      SizedBox(height: 8),
      InkWell(
        onTap: onPressed,
        child: Container(
          height: 50,
          padding: EdgeInsets.all(8),
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: Colors.white),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [Text(selectedText), Icon(Icons.arrow_drop_down_outlined)],
          ),
        ),
      )
    ]);
  }

  void _updateUserDetails() async {
    _userDetailModel.height = _heightValue;
    _userDetailModel.weight = _weightValue;
    _userDetailModel.firstName = _nameController.text;
    _userDetailModel.isWeightInKG = _isWeightKG;
    _userDetailModel.isHeightInCM = _isHeightCM;
    _userDetailModel.gender = _isGenderMale ? "M" : "F";

    var tempDate = DateUtil.convertDateToString(_dobDate);
    if (!tempDate.endsWith("/")) {
      tempDate = tempDate + "/";
    }

    _userDetailModel.dOB = tempDate;
    _userDetailModel.activityID = _selectedActiveLevel;
    GifLoaderDialogUtils.showMyDialog(context);
    await widget.viewModel.updateUserDetail(_userDetailModel, (tag) async {
      if (tag) {
        AppToast.showSuccessToast(message: TranslationBase.of(context).success);
        await prefs.setString(H2O_UNIT, _isUnitML ? "ml" : "l");
        int _tempRemindTime = prefs.getInt(H2O_REMINDER) ?? _selectedRemindedTime;
        if (_tempRemindTime != _selectedRemindedTime) {
          await prefs.setInt(H2O_REMINDER, _selectedRemindedTime);
          _addReminderToCalender(_selectedRemindedTime);
        }
      }
      GifLoaderDialogUtils.hideDialog(context);
    });

    Navigator.pop(context);
  }

  final CalendarPlugin _myPlugin = CalendarPlugin();
  void _addReminderToCalender(int _selectedRemindedTime) async {
    bool _calendarPermission = await _myPlugin.hasPermissions();
    if (_calendarPermission) {
    } else {
      await _myPlugin.requestPermissions();
    }
    _myPlugin.hasPermissions().then((value) {
      if (!value) {
        _myPlugin.requestPermissions();
      } else {
        _myPlugin.getCalendars().then((value) => {print(value.length)});
      }
    });
  }
}
