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/service/AnalyticsService.dart';
import 'package:doctor_app_flutter/core/viewModel/patient-referral-viewmodel.dart';
import 'package:doctor_app_flutter/locator.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/utils/date-utils.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/widgets/bottom_sheet/custom_bottom_sheet_container.dart';
import 'package:doctor_app_flutter/widgets/patients/patient-referral-item-widget.dart';
import 'package:doctor_app_flutter/widgets/patients/patient_service_title.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/app_bar/patient-profile-app-bar.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/dialogs/dailog-list-select.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';

class PatientMakeReferralScreen extends StatefulWidget {
  // previous design page is: ReferPatientScreen
  @override
  _PatientMakeReferralScreenState createState() => _PatientMakeReferralScreenState();
}

class _PatientMakeReferralScreenState extends State<PatientMakeReferralScreen> {
  PatiantInformtion? patient;
  List<dynamic>? referToList;
  dynamic _referTo;
  dynamic _selectedBranch;
  dynamic _selectedClinic;
  dynamic _selectedDoctor;
  DateTime? appointmentDate;
  final _remarksController = TextEditingController();

  String branchError = '';
  String hospitalError = '';
  String clinicError = '';
  String doctorError = '';

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

    appointmentDate = DateTime.now();
  }

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    patient = routeArgs['patient'];
    String patientType = routeArgs['patientType'];
    String arrivalType = routeArgs['arrivalType'];

    referToList = [];
    dynamic sameBranch = {"id": 1, "name": TranslationBase.of(context).sameBranch};
    dynamic otherBranch = {"id": 2, "name": TranslationBase.of(context).otherBranch};
    referToList!.add(sameBranch);
    referToList!.add(otherBranch);

    final screenSize = MediaQuery.of(context).size;

    return BaseView<PatientReferralViewModel>(
      onModelReady: (model) => model.getPatientReferral(patient!),
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        appBarTitle: TranslationBase.of(context).referPatient,
        isShowAppBar: true,
        appBar: PatientProfileAppBar(patient!),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ServiceTitle(
                        title: TranslationBase.of(context).refer,
                        subTitle: TranslationBase.of(context).patient,
                      ),
                    ),
                    model.patientReferral.length == 0
                        ? referralForm(model, screenSize)
                        : PatientReferralItemWidget(
                            referralStatus: model.patientReferral[model.patientReferral.length - 1].referralStatus!,
                            patientName: model.patientReferral[model.patientReferral.length - 1].patientName!,
                            patientGender: model.patientReferral[model.patientReferral.length - 1].patientDetails!.gender!,

                            ///TODO Elham*  check this
                            // referredDate: model
                            //     .patientReferral[
                            //         model.patientReferral.length - 1]
                            //     .referredOn
                            //     .split(" ")[0],
                            // referredTime: model
                            //     .patientReferral[
                            //         model.patientReferral.length - 1]
                            //     .referredOn
                            //     .split(" ")[1],
                            patientID: "${model.patientReferral[model.patientReferral.length - 1].patientID}",
                            isSameBranch: model.patientReferral[model.patientReferral.length - 1].isReferralDoctorSameBranch,
                            isReferral: true,
                            remark: model.patientReferral[model.patientReferral.length - 1].remarksFromSource,
                            nationality: model.patientReferral[model.patientReferral.length - 1].patientDetails!.nationalityName!,
                            nationalityFlag: model.patientReferral[model.patientReferral.length - 1].nationalityFlagUrl,
                            doctorAvatar: model.patientReferral[model.patientReferral.length - 1].doctorImageUrl!,
                            referralDoctorName: model.patientReferral[model.patientReferral.length - 1].referredByDoctorInfo!,
                            clinicDescription: "",
                          ),
                    SizedBox(
                      height: 10,
                    ),
                  ],
                ),
                if (model.patientReferral.length == 0)
                  CustomBottomSheetContainer(
                      label: "${TranslationBase.of(context).refer}",
                      onTap: () async {
                        await locator<AnalyticsService>().logEvent(
                          eventCategory: "Refer Patient",
                          eventAction: "Submit Refer",
                        );
                        if (_referTo == null) {
                          branchError = TranslationBase.of(context).fieldRequired;
                        } else {
                          branchError = "";
                        }
                        if (_selectedBranch == null) {
                          hospitalError = TranslationBase.of(context).fieldRequired;
                        } else {
                          hospitalError = "";
                        }
                        if (_selectedClinic == null) {
                          clinicError = TranslationBase.of(context).fieldRequired;
                        } else {
                          clinicError = "";
                        }
                        if (_selectedDoctor == null) {
                          doctorError = TranslationBase.of(context).fieldRequired;
                        } else {
                          doctorError = "";
                        }

                        if (appointmentDate == null || _selectedBranch == null || _selectedClinic == null || _selectedDoctor == null || _remarksController.text == null) return;
                        model
                            .makeReferral(
                                patient!, appointmentDate!.toIso8601String(), _selectedBranch['facilityId'], _selectedClinic['ClinicID'], _selectedDoctor['DoctorID'], _remarksController.text)
                            .then((_) {
                          DrAppToastMsg.showSuccesToast(TranslationBase.of(context).referralSuccessMsg);
                          Navigator.pop(context);
                        });
                      }),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget referralForm(PatientReferralViewModel model, Size screenSize) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 0, horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          AppTextFieldCustom(
            height: screenSize.height * 0.075,
            hintText: TranslationBase.of(context).branch,
            dropDownText: _referTo != null ? _referTo['name'] : null,
            enabled: false,
            isTextFieldHasSuffix: true,
            validationError: branchError,
            onClick: referToList != null
                ? () {
                    ListSelectDialog dialog = ListSelectDialog(
                      list: referToList!,
                      attributeName: 'name',
                      attributeValueId: 'id',
                      okText: TranslationBase.of(context).ok,
                      okFunction: (selectedValue) {
                        setState(() {
                          _referTo = selectedValue;
                          _selectedBranch = null;
                          _selectedClinic = null;
                          _selectedDoctor = null;
                          //handle the other branch data
                          if(_referTo['id'] == 2){

                            return;
                          }

                          model.getDoctorBranch().then((value) async {
                            _selectedBranch = value;
                            if (_referTo['id'] == 1) {
                              GifLoaderDialogUtils.showMyDialog(context);
                              await model.getClinics(_selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                              if (model.state == ViewState.ErrorLocal) {
                                DrAppToastMsg.showErrorToast(model.error);
                              }
                            } else {
                              _selectedBranch = null;
                            }
                          });
                        });
                      },
                    );
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return dialog;
                      },
                    );
                  }
                : () {},
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
          SizedBox(
            height: 10,
          ),
          AppTextFieldCustom(
            height: screenSize.height * 0.075,
            hintText: TranslationBase.of(context).hospital,
            dropDownText: _selectedBranch != null ? _selectedBranch['facilityName'] : null,
            enabled: false,
            isTextFieldHasSuffix: true,
            validationError: hospitalError,
            onClick: model.branchesList != null && model.branchesList!.length > 0 && _referTo != null && _referTo['id'] == 2
                ? () {
                    ListSelectDialog dialog = ListSelectDialog(
                      list: model.branchesList!,
                      attributeName: 'facilityName',
                      attributeValueId: 'facilityId',
                      okText: TranslationBase.of(context).ok,
                      okFunction: (selectedValue) async {
                        _selectedBranch = selectedValue;
                        _selectedClinic = null;
                        _selectedDoctor = null;
                        GifLoaderDialogUtils.showMyDialog(context);
                        await model.getClinics(_selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                        if (model.state == ViewState.ErrorLocal) {
                          DrAppToastMsg.showErrorToast(model.error);
                        }
                      },
                    );
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return dialog;
                      },
                    );
                  }
                : () {},
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
          SizedBox(
            height: 10,
          ),
          AppTextFieldCustom(
            height: screenSize.height * 0.075,
            hintText: TranslationBase.of(context).clinic,
            dropDownText: _selectedClinic != null ? _selectedClinic['ClinicDescription'] : null,
            enabled: false,
            isTextFieldHasSuffix: true,
            validationError: clinicError,
            onClick: _selectedBranch != null && model.clinicsList != null && model.clinicsList!.length > 0
                ? () {
                    ListSelectDialog dialog = ListSelectDialog(
                      list: model.clinicsList!,
                      attributeName: 'ClinicDescription',
                      attributeValueId: 'ClinicID',
                      usingSearch: true,
                      hintSearchText: TranslationBase.of(context).clinicSearch,
                      okText: TranslationBase.of(context).ok,
                      okFunction: (selectedValue) async {
                        _selectedDoctor = null;
                        _selectedClinic = selectedValue;
                        GifLoaderDialogUtils.showMyDialog(context);
                        await model.getClinicDoctors(patient!, _selectedClinic['ClinicID'], _selectedBranch['facilityId']).then((_) => GifLoaderDialogUtils.hideDialog(context));
                        if (model.state == ViewState.ErrorLocal) {
                          DrAppToastMsg.showErrorToast(model.error);
                        }
                      },
                    );
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return dialog;
                      },
                    );
                  }
                : () {},
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
          SizedBox(
            height: 10,
          ),
          AppTextFieldCustom(
            height: screenSize.height * 0.075,
            hintText: TranslationBase.of(context).doctor,
            dropDownText: _selectedDoctor != null ? _selectedDoctor['Name'] : null,
            enabled: false,
            isTextFieldHasSuffix: true,
            validationError: doctorError,
            onClick: _selectedClinic != null && model.doctorsList != null && model.doctorsList.length > 0
                ? () {
                    ListSelectDialog dialog = ListSelectDialog(
                      list: model.doctorsList,
                      attributeName: 'Name',
                      attributeValueId: 'DoctorID',
                      usingSearch: true,
                      hintSearchText: TranslationBase.of(context).doctorSearch,
                      okText: TranslationBase.of(context).ok,
                      okFunction: (selectedValue) {
                        setState(() {
                          _selectedDoctor = selectedValue;
                        });
                      },
                    );
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return dialog;
                      },
                    );
                  }
                : () {
                    if (_selectedClinic == null) {
                      DrAppToastMsg.showErrorToast("You need to select a clinic first");
                    } else if (model.doctorsList == null || model.doctorsList.length == 0) {
                      DrAppToastMsg.showErrorToast("There is no doctors for this clinic");
                    }
                  },
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
          SizedBox(
            height: 10,
          ),
          AppTextFieldCustom(
            height: screenSize.height * 0.075,
            hintText: TranslationBase.of(context).date,
            dropDownText: appointmentDate != null ? "${AppDateUtils.convertDateToFormat(appointmentDate!, "yyyy-MM-dd")}" : "",
            enabled: false,
            isTextFieldHasSuffix: true,
            suffixIcon: IconButton(
              icon: Icon(
                Icons.calendar_today,
                color: Colors.black,
              ),
              onPressed: () {},
            ),
            onClick: () {
              _selectDate(context, model);
            },
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
          SizedBox(
            height: 10,
          ),
          AppTextFieldCustom(
            hintText: TranslationBase.of(context).dietTypeRemarks,
            controller: _remarksController,
            inputType: TextInputType.multiline,
            minLines: 4,
            maxLines: 6,
            onClick: () {},
            onChanged: (value) {},
            onFieldSubmitted: () {},
          ),
        ],
      ),
    );
  }

  _selectDate(BuildContext context, PatientReferralViewModel model) async {
    // https://medium.com/flutter-community/a-deep-dive-into-datepicker-in-flutter-37e84f7d8d6c   good reference
    // https://stackoverflow.com/a/63147062/6246772  to customize a date picker
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: appointmentDate,
      firstDate: DateTime.now().add(Duration(hours: 2)),
      lastDate: DateTime(2040),
      initialEntryMode: DatePickerEntryMode.calendar,
    );
    if (picked != null && picked != appointmentDate) {
      setState(() {
        appointmentDate = picked;
      });
    }
  }
}
