import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/config/shared_pref_kay.dart';
import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/sick_leave_view_model.dart';
import 'package:doctor_app_flutter/models/sickleave/add_sickleave_request.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/sick-leave/add-sickleave.dart';
import 'package:doctor_app_flutter/util/dr_app_shared_pref.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/text_validator.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/patient-page-header-widget.dart';
import 'package:doctor_app_flutter/widgets/shared/Text.dart';
import 'package:doctor_app_flutter/widgets/shared/app_buttons_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_text_form_field.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/rounded_container_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
import 'package:doctor_app_flutter/models/sickleave/get_all_sickleave_response.dart';

Helpers helpers = Helpers();

class SickLeaveScreen extends StatefulWidget {
  final bool isExtended;
  final GetAllSickLeaveResponse extendedData;
  final appointmentNo;
  final patientMRN;
  final patient;
  SickLeaveScreen(
      {this.appointmentNo,
      this.patientMRN,
      this.isExtended = false,
      this.extendedData,
      this.patient});
  @override
  _SickLeaveScreenState createState() => _SickLeaveScreenState();
}

class _SickLeaveScreenState extends State<SickLeaveScreen> {
  DrAppSharedPreferances sharedPref = new DrAppSharedPreferances();
  TextEditingController _toDateController = new TextEditingController();
  String _selectedClinic;
  Map profile = {};
  AddSickLeaveRequest addSickLeave = AddSickLeaveRequest();
  void _presentDatePicker(id) {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2019),
      lastDate: DateTime(2050),
    ).then((pickedDate) {
      if (pickedDate == null) {
        return;
      }
      setState(() {
        // var selectedDate = DateFormat.yMd().format(pickedDate);
        final df = new DateFormat('yyyy-MM-dd');
        addSickLeave.startDate = df.format(pickedDate);

        _toDateController.text = addSickLeave.startDate;
        //addSickLeave.startDate = selectedDate;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return BaseView<PatientViewModel>(
        onModelReady: (model) => model.getClinicsList(),
        builder: (_, model, w) => BaseView<SickLeaveViewModel>(
            onModelReady: (model2) => model2.preSickLeaveStatistics(
                widget.appointmentNo, widget.patientMRN),
            builder: (_, model2, w) => GestureDetector(
                  onTap: () {
                    FocusScope.of(context).requestFocus(new FocusNode());
                  },
                  child: AppScaffold(
                    baseViewModel: model2,
                    isShowAppBar: false,
                    body: Center(
                      child: Container(
                        margin: EdgeInsets.only(top: 10),
                        child: FractionallySizedBox(
                          widthFactor: 0.9,
                          child: ListView(
                            children: [
                              Padding(
                                  child: AppText(
                                    widget.isExtended == true
                                        ? TranslationBase.of(context)
                                            .extendSickLeave
                                        : TranslationBase.of(context)
                                            .addSickLeave,
                                    fontWeight: FontWeight.bold,
                                  ),
                                  padding: EdgeInsets.all(10)),
                              Container(
                                margin: EdgeInsets.only(left: 10, right: 10),
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6.0)),
                                    border: Border.all(
                                        width: 1.0,
                                        color: HexColor("#CCCCCC"))),
                                padding: EdgeInsets.all(5),
                                child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      AppTextFormField(
                                          borderColor: Colors.white,
                                          onChanged: (value) {
                                            addSickLeave.noOfDays = value;
                                            if (widget.extendedData != null) {
                                              widget.extendedData.noOfDays =
                                                  int.parse(value);
                                            }
                                          },
                                          hintText: widget.extendedData != null
                                              ? widget.extendedData.noOfDays
                                                  .toString()
                                              : TranslationBase.of(context)
                                                  .sickLeaveDays,
                                          // validator: (value) {
                                          //   return TextValidator().validateName(value);
                                          // },
                                          inputFormatter: ONLY_NUMBERS)
                                    ]),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Container(
                                  margin: EdgeInsets.only(left: 10, right: 10),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  padding: EdgeInsets.all(5),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      // AppText(
                                      //   TranslationBase.of(context).sickLeaveDate,
                                      //   fontSize: 10,
                                      // ),
                                      AppTextFormField(
                                          hintText: widget.extendedData != null
                                              ? widget.extendedData.startDate
                                              : TranslationBase.of(context)
                                                  .sickLeaveDate,
                                          borderColor: Colors.white,
                                          prefix: IconButton(
                                              icon: Icon(Icons.calendar_today)),
                                          textInputType: TextInputType.number,
                                          controller: _toDateController,
                                          onTap: () {
                                            _presentDatePicker(
                                                '_selectedToDate');
                                          },
                                          inputFormatter: ONLY_DATE,
                                          onChanged: (value) {
                                            addSickLeave.startDate = value;
                                            if (widget.extendedData != null) {
                                              widget.extendedData.startDate =
                                                  value;
                                            }
                                          }),
                                    ],
                                  )),
                              Container(
                                  margin: EdgeInsets.only(
                                      top: 10, left: 10, right: 10),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(6.0)),
                                      border: Border.all(
                                          width: 1.0,
                                          color: HexColor("#CCCCCC"))),
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                        top: SizeConfig.widthMultiplier * 0.9,
                                        bottom:
                                            SizeConfig.widthMultiplier * 0.9,
                                        right: SizeConfig.widthMultiplier * 3,
                                        left: SizeConfig.widthMultiplier * 3),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        // AppText(
                                        //   TranslationBase.of(context).clinicName,
                                        //   fontSize: 10,
                                        // ),
                                        Row(
                                          mainAxisSize: MainAxisSize.max,
                                          children: <Widget>[
                                            Expanded(
                                              // add Expanded to have your dropdown button fill remaining space
                                              child:
                                                  DropdownButtonHideUnderline(
                                                      child: new IgnorePointer(
                                                          ignoring: true,
                                                          child: DropdownButton(
                                                            isExpanded: true,
                                                            value: getClinicName(
                                                                    model) ??
                                                                "",
                                                            iconSize: 0,
                                                            elevation: 16,
                                                            selectedItemBuilder:
                                                                (BuildContext
                                                                    context) {
                                                              return model
                                                                  .getClinicNameList()
                                                                  .map((item) {
                                                                return Row(
                                                                  mainAxisSize:
                                                                      MainAxisSize
                                                                          .max,
                                                                  children: <
                                                                      Widget>[
                                                                    AppText(
                                                                      item,
                                                                      fontSize:
                                                                          SizeConfig.textMultiplier *
                                                                              2.1,
                                                                      color: Colors
                                                                          .grey,
                                                                    ),
                                                                  ],
                                                                );
                                                              }).toList();
                                                            },
                                                            onChanged:
                                                                (newValue) =>
                                                                    {},
                                                            items: model
                                                                .getClinicNameList()
                                                                .map((item) {
                                                              return DropdownMenuItem(
                                                                value: item
                                                                    .toString(),
                                                                child: Text(
                                                                  item,
                                                                  textAlign:
                                                                      TextAlign
                                                                          .end,
                                                                ),
                                                              );
                                                            }).toList(),
                                                          ))),
                                            ),
                                          ],
                                        )
                                      ],
                                    ),
                                  )),
                              model2.sickLeaveStatistics[
                                          'recommendedSickLeaveDays'] !=
                                      null
                                  ? Padding(
                                      child: AppText(
                                        model2.sickLeaveStatistics[
                                            'recommendedSickLeaveDays'],
                                        fontWeight: FontWeight.bold,
                                        textAlign: TextAlign.start,
                                      ),
                                      padding: EdgeInsets.all(10),
                                    )
                                  : SizedBox(
                                      height: 10,
                                    ),
                              Container(
                                margin: EdgeInsets.only(left: 10, right: 10),
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6.0)),
                                    border: Border.all(
                                        width: 1.0,
                                        color: HexColor("#CCCCCC"))),
                                padding: EdgeInsets.all(5),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // AppText(
                                    //   TranslationBase.of(context).doctorName,
                                    //   fontSize: 10,
                                    // ),
                                    new IgnorePointer(
                                        ignoring: true,
                                        child: AppTextFormField(
                                            readOnly: true,
                                            hintText: profile['DoctorName'],
                                            borderColor: Colors.white,
                                            onSaved: (value) {},
                                            // validator: (value) {
                                            //   return TextValidator().validateName(value);
                                            // },
                                            inputFormatter: ONLY_NUMBERS))
                                  ],
                                ),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 10, right: 10),
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(6.0)),
                                    border: Border.all(
                                        width: 1.0,
                                        color: HexColor("#CCCCCC"))),
                                padding: EdgeInsets.all(5),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // AppText(
                                    //   TranslationBase.of(context).remarks,
                                    //   fontSize: 10,
                                    // ),
                                    TextField(
                                      maxLines: 3,
                                      decoration: InputDecoration(
                                          contentPadding: EdgeInsets.all(20.0),
                                          border: InputBorder.none,
                                          hintText: widget.extendedData != null
                                              ? widget.extendedData.remarks
                                              : TranslationBase.of(context)
                                                  .remarks),
                                      onChanged: (value) {
                                        addSickLeave.remarks = value;
                                        if (widget.extendedData != null) {
                                          widget.extendedData.remarks = value;
                                        }
                                      },
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.all(
                                    SizeConfig.widthMultiplier * 5),
                                child: Wrap(
                                  alignment: WrapAlignment.center,
                                  children: <Widget>[
                                    AppButton(
                                      title: widget.isExtended == true
                                          ? TranslationBase.of(context).extend
                                          : TranslationBase.of(context).add,
                                      onPressed: () async {
                                        if (widget.isExtended) {
                                          await model2.extendSickLeave(
                                              widget.extendedData);

                                          DrAppToastMsg.showSuccesToast(
                                              model2.sickleaveResponse[
                                                      'ListSickLeavesToExtent']
                                                  ['success']);
                                          Navigator.of(context)
                                              .popUntil((route) {
                                            return route.settings.name ==
                                                PATIENTS_PROFILE;
                                          });
                                          Navigator.of(context).pushNamed(
                                              ADD_SICKLEAVE,
                                              arguments: {
                                                'patient': widget.patient
                                              });
                                          //print(value);
                                          //});
                                        } else {
                                          _validateInputs(model2);
                                        }
                                      },
                                    ),
                                  ],
                                ),
                              ),
                              // Column(
                              //   children: [
                              //     Texts(TranslationBase.of(context)
                              //             .previousSickLeaveIssue +
                              //         ' ')
                              //   ],
                              // )
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                )));
  }

  void _validateInputs(model2) async {
    try {
      if (addSickLeave.noOfDays == null) {
        DrAppToastMsg.showErrorToast(
            TranslationBase.of(context).pleaseEnterNoOfDays);
      } else if (addSickLeave.remarks == null) {
        DrAppToastMsg.showErrorToast(
            TranslationBase.of(context).pleaseEnterRemarks);
      } else if (addSickLeave.startDate == null) {
        DrAppToastMsg.showErrorToast(
            TranslationBase.of(context).pleaseEnterDate);
      } else {
        addSickLeave.patientMRN = widget.patient.patientMRN.toString();
        addSickLeave.appointmentNo = widget.patient.appointmentNo.toString();
        await model2.addSickLeave(addSickLeave).then((value) => print(value));

        DrAppToastMsg.showSuccesToast(
            model2.sickleaveResponse['ListSickLeavesToExtent']['success']);
        Navigator.of(context).popUntil((route) {
          return route.settings.name == PATIENTS_PROFILE;
        });
        Navigator.of(context)
            .pushNamed(ADD_SICKLEAVE, arguments: {'patient': widget.patient});
      }
    } catch (err) {
      print(err);
    }
  }

  getProfile() async {
    Map p = await sharedPref.getObj(DOCTOR_PROFILE);
    setState(() {
      this.profile = p;
    });
  }

  getClinicName(model) {
    var clinicInfo = model.clinicsList
        .where((i) => i['ClinicID'] == this.profile['ClinicID'])
        .toList();
    return clinicInfo.length > 0 ? clinicInfo[0]['ClinicDescription'] : "";
  }
}
