import 'package:device_calendar/device_calendar.dart';
import 'package:hmg_patient_app/core/model/childvaccines/List_BabyInformationModel.dart';
import 'package:hmg_patient_app/core/model/childvaccines/add_newchild_model.dart';
import 'package:hmg_patient_app/core/model/childvaccines/create_new_user_model.dart';
import 'package:hmg_patient_app/core/model/childvaccines/user_information_model.dart';
import 'package:hmg_patient_app/core/viewModels/child_vaccines/add_new_child_view_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/pages/medical/active_medications/DayCheckBoxDialog.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';

enum Gender { Male, Female, NON }
enum BeneficiaryType { MyAccount, MyFamilyFiles, OtherAccount, NON }

class AddNewChildPage extends StatefulWidget {
  final int? frequency;
  final int? days;
  final String? itemDescription;
  String? dateAdd;

  List<DateTime> _scheduleList =[];
  List<DayOfWeek> daysOfWeek = [DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday];

  DateTime? startDay;
  DateTime? endDay;

  //AddNewChildPage({Key key, this.frequency, this.days, this.itemDescription}) : super(key: key);
  AddNewChildPage({Key? key, this.frequency, this.days, this.itemDescription}) {
    startDay = DateTime.now();
    endDay = DateTime.now(); //endDay = DateTime.now().add(Duration(days: days));
    int hour = 24; //(24 / frequency).round();
    int durations = 24 ~/ hour;
    for (int count = 0; count < durations; count++) {
      _scheduleList.add(DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, (hour * count)));
    }
  }

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

class _AddNewChildPageState extends State<AddNewChildPage> {
 late  int tappedIndex;
   int checkedValue =0;

  @override
  void initState() {
    super.initState();
    tappedIndex = -1;
  }

  TextEditingController _firstTextController = TextEditingController();
  TextEditingController _secondTextController = TextEditingController();
  TextEditingController _notesTextController = TextEditingController();
  BeneficiaryType beneficiaryType = BeneficiaryType.NON;
  Gender gender = Gender.Male;
  CreateNewUser_New newUserChild = CreateNewUser_New();

  //ChildVaccinesViewModel addvancedModel = ChildVaccinesViewModel();
  List_BabyInformationModel addvancedModel = List_BabyInformationModel();
  CreateNewBaby newChild = CreateNewBaby();
  List_UserInformationModel informationModel = List_UserInformationModel();

  @override
  Widget build(BuildContext context) {
    return BaseView<AddNewChildViewModel>(
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).vaccination,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        body: Container(
          child: Column(
            children: [
              Expanded(
                child: Padding(
                  padding: EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        TranslationBase.of(context).vaccinationAddChildMsg,
                        //+model.user.firstName,
                        style: TextStyle(
                          fontSize: 16,
                          letterSpacing: -0.64,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),
                      inputWidget(TranslationBase.of(context).firstName, "", _firstTextController),
                      SizedBox(
                        height: 12,
                      ),
                      inputWidget(TranslationBase.of(context).middleName, "", _secondTextController),

                      SizedBox(
                        height: 12,
                      ),
                      Text(
                        TranslationBase.of(context).selectGender,
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          letterSpacing: -0.48,
                        ),
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Row(
                              children: [
                                Radio(
                                    value: checkedValue,
                                    groupValue: 1,
                                    onChanged: (v) {
                                      setState(() {
                                        checkedValue = 1;
                                      });
                                    }),
                                Text(
                                  TranslationBase.of(context).male,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    fontWeight: FontWeight.w600,
                                  ),
                                )
                              ],
                            ),
                          ),
                          Expanded(
                            child: Row(
                              children: [
                                Radio(
                                    value: checkedValue,
                                    groupValue: 2,
                                    onChanged: (v) {
                                      setState(() {
                                        checkedValue = 2;
                                      });
                                    }),
                                Text(
                                  TranslationBase.of(context).female,
                                  style: TextStyle(
                                    fontSize: 12,
                                    letterSpacing: -0.48,
                                    fontWeight: FontWeight.w600,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ],
                      ),

                      //==========
                      SizedBox(
                        height: 6,
                      ),

                      InkWell(
                        onTap: () {
                          DatePicker.showDatePicker(
                            context,
                            showTitleActions: true,
                            // minTime: DateTime(
                            //     DateTime.now().year, DateTime.now().month - 1, 1),
                            minTime: DateTime(1, 1, 1),
                            maxTime: DateTime.now(),
                            onConfirm: (date) {
                              setState(() {
                                widget.startDay = date;
                              });
                            },
                            currentTime: widget.startDay,
                            // locale: projectViewModel.localeType
                          );
                        },
                        child: Container(
                          width: double.infinity,
                          padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15),
                            color: Colors.white,
                            border: Border.all(
                              color: Color(0xffefefef),
                              width: 1,
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Text(
                                    TranslationBase.of(context).dob,
                                    style: TextStyle(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff2B353E),
                                      letterSpacing: -0.44,
                                    ),
                                  ),
                                  Text(
                                    //getStartDay()
                                    // DateUtil.yearMonthDay(DateTime.now())
                                    getStartDay(),
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 21 / 14,
                                      fontWeight: FontWeight.w400,
                                      color: Color(0xff575757),
                                      letterSpacing: -0.56,
                                    ),
                                  ),
                                ],
                              ),
                              Icon(
                                Icons.calendar_today,
                                color: Color(0xff575757),
                                size: 18,
                              )
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),

                      //=========
                    ],
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.all(16),
                color: Colors.white,
                child: DefaultButton(
                  TranslationBase.of(context).add,
                  () async {
                    newChild.babyName = _firstTextController.text + " " + _secondTextController.text;
                    newChild.gender = checkedValue.toString();
                    newChild.strDOB = getStartDay();
                    newChild.tempValue = true;
                    newChild.isLogin = true;

                    await model.createNewBabyOrders(newChild: newChild);
                    if (model.isAdded) {
                      AppToast.showSuccessToast(message: TranslationBase.of(context).childAddedSuccessfully);
                      Navigator.pop(context, model.isAdded);
                    } else {
                      //TODO handling error
                    }
                  },
                ),
              ),
            ],
          ),
        ),
        // bottomSheet:
      ),
    );
  }

  String getStartDay() {
    return "${DateUtil.getMonth(widget.startDay!.month)} ${widget.startDay!.day}, ${widget.startDay!.year}";
  }

  String getEndDay() {
    return "${DateUtil.getMonth(widget.endDay!.month)} ${widget.endDay!.day}, ${widget.endDay!.year}";
  }

  String getDateTime(DateTime dateTime) {
    return '${dateTime.hour}:${dateTime.minute}';
  }

  String getDays() {
    String days = "";
    widget.daysOfWeek.forEach((element) {
      days += "${DateUtil.getDay(element)},";
    });
    return days;
  }

  void confirmSelectDayDialog() {
    showDialog(
      context: context,
      builder: (cxt) => DayCheckBoxDialog(
        title: 'Select Day',
        selectedDaysOfWeek: widget.daysOfWeek,
        onValueSelected: (value) {
          setState(() {
            widget.daysOfWeek = value;
          });
        },
      ),
    );
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller,
      {VoidCallback? suffixTap, bool isEnable = true, bool hasSelection = false, int? lines, bool isInputTypeNum = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.zero,
                    keyboardType: isInputTypeNum ? TextInputType.number : TextInputType.text,
                    controller: _controller,
                    maxLines: lines,
                    onChanged: (value) => {setState(() {})},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      hintStyle: TextStyle(
                        fontSize: 14,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: Color(0xff575757),
                        letterSpacing: -0.56,
                      ),
                      suffixIconConstraints: BoxConstraints(minWidth: 50),
                      suffixIcon: suffixTap == null ? null : IconButton(icon: Icon(Icons.mic, color: Color(0xff2E303A)), onPressed: suffixTap),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }
}
