import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/core/model/sickleave/add_sickleave_request.dart';
import 'package:doctor_app_flutter/core/viewModel/sick_leave_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/soap_update/shared_soap_widgets/bottom_sheet_title.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/utils/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/buttons/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app-textfield-custom.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';

Utils helpers = Utils();

class AddPatientSickLeaveScreen extends StatefulWidget {
  final appointmentNo;
  final patientMRN;
  final PatiantInformtion? patient;
  final SickLeaveViewModel? previousModel;

  AddPatientSickLeaveScreen({this.appointmentNo, this.patientMRN, this.patient, this.previousModel});

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

class _AddPatientSickLeaveScreenState extends State<AddPatientSickLeaveScreen> {
  DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
  TextEditingController _toDateController = new TextEditingController();
  TextEditingController _numberOfDayController = new TextEditingController();
  TextEditingController _clinicController = new TextEditingController();
  TextEditingController _doctorController = new TextEditingController();
  TextEditingController _remarkController = new TextEditingController();
  DateTime? currentDate;

  AddSickLeaveRequest addSickLeave = AddSickLeaveRequest();
  bool isFormSubmitted = false;

  void _presentDatePicker() {
    showDatePicker(
      context: context,
      initialDate: currentDate ?? DateTime.now(),
      firstDate: AppDateUtils.convertStringToDate(
        widget!.patient!.arrivedOn!,
      ),
      lastDate: DateTime(DateTime.now().year + 1),
    ).then((pickedDate) {
      if (pickedDate == null) {
        return;
      }
      setState(() {
        final df = new DateFormat('yyyy-MM-dd');
        addSickLeave.startDate = df.format(pickedDate);
        currentDate = pickedDate;
        _toDateController.text = AppDateUtils.getDayMonthYearDateFormatted(pickedDate, isMonthShort: true);
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return BaseView<SickLeaveViewModel>(
        onModelReady: (model) async {
          await model.getDoctorProfile();
          _clinicController.text = model.doctorProfile!.clinicDescription!;
          _doctorController.text = model.doctorProfile!.doctorName!;
          await model.preSickLeaveStatistics(widget.appointmentNo, widget.patientMRN);
        },
        builder: (_, model, w) => GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(new FocusNode());
              },
              child: AppScaffold(
                  baseViewModel: model,
                  appBar: BottomSheetTitle(
                    title: TranslationBase.of(context).addSickLeave,
                  ),
                  isShowAppBar: true,
                  body: Center(
                    child: Container(
                      margin: EdgeInsets.only(top: 10),
                      child: FractionallySizedBox(
                        widthFactor: 0.9,
                        child: ListView(
                          children: [
                            SizedBox(
                              height: 30,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              hintText: TranslationBase.of(context).sickLeave + ' ' + TranslationBase.of(context).days,
                              maxLines: 1,
                              minLines: 1,
                              dropDownColor: Colors.white,
                              isTextFieldHasSuffix: true,
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(ONLY_NUMBERS))],
                              inputType: TextInputType.number,
                              controller: _numberOfDayController,
                              onChanged: (value) {
                                if (value != null)
                                  setState(() {
                                    addSickLeave.noOfDays = value;
                                  });
                              },
                              validationError: isFormSubmitted && (addSickLeave.noOfDays == null) ? TranslationBase.of(context).pleaseEnterNoOfDays : null,
                              onClick: () {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              onClick: () {
                                Utils.hideKeyboard(context);
                                _presentDatePicker();
                              },
                              hintText: TranslationBase.of(context).sickLeaveDate,
                              enabled: false,
                              maxLines: 1,
                              minLines: 1,
                              isTextFieldHasSuffix: true,
                              suffixIcon: IconButton(
                                icon: Icon(Icons.calendar_today),
                                onPressed: () {},
                              ),
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(ONLY_NUMBERS))],
                              controller: _toDateController,
                              onChanged: (value) {
                                setState(() {
                                  addSickLeave.startDate = value;
                                });
                              },
                              validationError: isFormSubmitted && (addSickLeave.startDate == null) ? TranslationBase.of(context).pleaseEnterDate : null,
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 5,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              hintText: TranslationBase.of(context).clinic,
                              enabled: false,
                              maxLines: 1,
                              minLines: 1,
                              dropDownColor: Colors.white,
                              isTextFieldHasSuffix: true,
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(ONLY_NUMBERS))],
                              controller: _clinicController,
                              onChanged: (value) {},
                              onClick: () {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            model.sickLeaveStatistics.recommendedSickLeaveDays != null
                                ? Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Icon(
                                        DoctorApp.warning,
                                        size: 20,
                                        color: AppGlobal.inProgressColor,
                                      ),
                                      SizedBox(
                                        width: 10,
                                      ),
                                      Expanded(
                                        child: AppText(
                                          model.sickLeaveStatistics.recommendedSickLeaveDays!,
                                          textAlign: TextAlign.start,
                                          fontSize: 12,
                                          color: AppGlobal.inProgressColor,
                                        ),
                                      ),
                                    ],
                                  )
                                : SizedBox(
                                    height: 10,
                                  ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              hintText: TranslationBase.of(context).doctor,
                              enabled: false,
                              maxLines: 1,
                              minLines: 1,
                              dropDownColor: Colors.white,
                              isTextFieldHasSuffix: true,
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(ONLY_NUMBERS))],
                              controller: _doctorController,
                              onChanged: (value) {},
                              onClick: () {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            AppTextFieldCustom(
                              height: Utils.getTextFieldHeight(),
                              hintText: TranslationBase.of(context).remarks,
                              maxLines: 30,
                              minLines: 5,
                              dropDownColor: Colors.white,
                              isTextFieldHasSuffix: true,
                              controller: _remarkController,
                              onChanged: (value) {
                                setState(() {
                                  addSickLeave.remarks = value;
                                });
                              },
                              onClick: () {},
                              onFieldSubmitted: () {},
                            ),
                            SizedBox(
                              height: SizeConfig.heightMultiplier! * (SizeConfig.isHeightVeryShort ? 12 : 10) + 20,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  bottomSheet: model.state == ViewState.Busy || model.state == ViewState.Busy
                      ? Container(
                          height: 0,
                        )
                      : Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(
                              Radius.circular(0.0),
                            ),
                            border: Border.all(color: HexColor('#707070'), width: 0),
                          ),
                          height: SizeConfig.heightMultiplier! * (SizeConfig.isHeightVeryShort ? 12 : 10),
                          width: double.infinity,
                          child: Column(
                            children: [
                              SizedBox(
                                height: 10,
                              ),
                              FractionallySizedBox(
                                widthFactor: 0.9,
                                child: AppButton(
                                    title: TranslationBase.of(context).addSickLeaverequest,
                                    color: AppGlobal.appGreenColor,
                                    onPressed: () async {
                                      submitForm(model);
                                    }),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                            ],
                          ),
                        )),
            ));
  }

  submitForm(SickLeaveViewModel model) async {
    {
      try {
        setState(() {
          isFormSubmitted = true;
        });
        if (addSickLeave.noOfDays == null || addSickLeave.startDate == null) {
          return;
        } else {
          GifLoaderDialogUtils.showMyDialog(context);
          addSickLeave.patientMRN = widget.patient!.patientMRN.toString();
          addSickLeave.appointmentNo = widget.patient!.appointmentNo.toString();
          await model.addSickLeave(addSickLeave);
          print("the state is ${model.state}");
          if (model.state == ViewState.ErrorLocal) {
            Utils.showErrorToast(model.error);
          } else {
            await widget.previousModel!.getSickLeaveForPatient(widget.patient!, isLocalBusy: true);
            DrAppToastMsg.showSuccesToast(TranslationBase.of(context).replySuccessfully);
            Navigator.of(context).pop();
          }

          GifLoaderDialogUtils.hideDialog(context);
        }
      } catch (err) {
        print(err);
      }
    }
  }
}
