import 'package:hmg_patient_app/core/service/medical/ask_doctor_services.dart';
import 'package:hmg_patient_app/core/viewModels/medical/ask_doctor_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/pages/BookAppointment/widgets/DoctorView.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/pages/medical/ask_doctor/request_type.dart';
import 'package:hmg_patient_app/theme/colors.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/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/others/app_expandable_notifier.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AskDoctorPage extends StatelessWidget {
  AskDoctorService service = new AskDoctorService();

  @override
  Widget build(BuildContext context) {
    return BaseView<AskDoctorViewModel>(
      onModelReady: (model) => model.getMyDoctor(),
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        body: model.patientDoctorAppointmentListHospital.length > 0 ? _appointmentExpandableList(model.patientDoctorAppointmentListHospital, model) : noDoctor(context),
      ),
    );
  }

  Widget noDoctor(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 50.0, right: 50.0),
      child: Center(
        child: Text(TranslationBase.of(context).askDocEmpty, textAlign: TextAlign.center, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: CustomColors.accentColor)),
      ),
    );
  }

  Widget _appointmentExpandableList(List<PatientDoctorAppointmentList> _patientDoctorAppointmentList, model) {
    return ListView.separated(
      addAutomaticKeepAlives: true,
      physics: BouncingScrollPhysics(),
      padding: EdgeInsets.only(top: 12),
      separatorBuilder: (context, index) {
        return Container(
          height: 12,
          margin: EdgeInsets.only(left: 21, right: 21),
          // color: Color(0xffD9D9D9),
        );
      },
      itemBuilder: (context, index) {
        List<DoctorList> _doctorList = _patientDoctorAppointmentList[index].patientDoctorAppointmentList!;
        return AppExpandableNotifier(
          title: _patientDoctorAppointmentList[index].filterName,
          bodyWidget: ListView.separated(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
              itemBuilder: (context, _index) {
                DoctorList _doctor = _doctorList[_index];
                DoctorList doctorList = DoctorList(
                    date: _doctor.date,
                    projectID: _doctor.projectID,
                    setupID: _doctor.setupID,
                    clinicID: _doctor.clinicID,
                    projectName: _doctor.projectName,
                    clinicName: _doctor.clinicName,
                    actualDoctorRate: _doctor.actualDoctorRate,
                    doctorID: _doctor.doctorID,
                    doctorRate: _doctor.doctorRate,
                    gender: _doctor.gender,
                    doctorTitle: _doctor.doctorTitle,
                    name: _doctor.name,
                    speciality: _doctor.speciality,
                    doctorImageURL: _doctor.doctorImageURL,
                    nationalityFlagURL: _doctor.nationalityFlagURL);
                return DoctorView(
                  doctor: doctorList,
                  isLiveCareAppointment: false,
                  isShowFlag: false,
                  onTap: () async {
                    if (await checkIfDoctorAvailable(_doctor, context)) {
                      GifLoaderDialogUtils.showMyDialog(context);
                      service.getCallInfoHoursResult(doctorId: _doctor.doctorID, projectId: _doctor.projectID).then((res) {
                        GifLoaderDialogUtils.hideDialog(context);
                        Navigator.push(
                          context,
                          FadePage(
                            page: RequestTypePage(doctorList: _doctor),
                          ),
                        );
                      }).catchError((err) {
                        GifLoaderDialogUtils.hideDialog(context);
                        if (err != null) AppToast.showErrorToast(message: err.toString());
                        print(err);
                      });
                    }
                  },
                );
              },
              separatorBuilder: (context, index) => SizedBox(height: 14),
              itemCount: _doctorList.length),
        );
      },
      itemCount: _patientDoctorAppointmentList.length,
    );
  }

  Future<bool> checkIfDoctorAvailable(DoctorList _doctor, BuildContext context) async {
    AskDoctorService askDocservice = new AskDoctorService();
    bool isAvailable = false;
    GifLoaderDialogUtils.showMyDialog(context);
    await askDocservice.isDoctorAvailable(doctorId: _doctor.doctorID, projectId: _doctor.projectID, clinicId: _doctor.clinicID).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res != null) {
        print(res['IsDoctorAvailable']);
        if (res['IsDoctorAvailable']) {
          isAvailable = true;
        } else {
          isAvailable = false;
          AppToast.showErrorToast(message: res['endUserMessage'], localContext: context);
        }
      } else {
        isAvailable = true;
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      if (err != null) AppToast.showErrorToast(message: err.toString(), localContext: context);
      print(err);
    });

    return Future.value(isAvailable);
  }

  String getDate(String date) {
    DateTime dateObj = DateUtil.convertStringToDate(date);
    return DateUtil.getWeekDay(dateObj.weekday) +
        ", " +
        dateObj.day.toString() +
        " " +
        DateUtil.getMonth(dateObj.month) +
        " " +
        dateObj.year.toString() +
        " " +
        dateObj.hour.toString() +
        ":" +
        getMinute(dateObj);
  }

  String getMinute(DateTime dateObj) {
    if (dateObj.minute == 0) {
      return dateObj.minute.toString() + "0";
    } else {
      return dateObj.minute.toString();
    }
  }
}
