import 'package:hmg_patient_app/analytics/google-analytics.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/Appointments/DentalChiefComplaintsModel.dart';
import 'package:hmg_patient_app/models/Appointments/DentalProceduresModel.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/models/Appointments/SearchInfoModel.dart';
import 'package:hmg_patient_app/pages/BookAppointment/widgets/DentalComplaintCard.dart';
import 'package:hmg_patient_app/pages/BookAppointment/widgets/DoctorView.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.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/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.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:flutter/material.dart';
import 'package:provider/provider.dart';

class DentalComplaints extends StatefulWidget {
  SearchInfo searchInfo;
  Function? onSelectedMethod;
  bool isDoctorNameSearch;
  bool isFromHospitalSearchPage;

  DentalComplaints({required this.searchInfo, this.onSelectedMethod, this.isDoctorNameSearch = false, this.isFromHospitalSearchPage = false});

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

class _DentalComplaintsState extends State<DentalComplaints> {
  List<ListDentalChiefComplain> complaintsList = [];
  AppSharedPreferences sharedPref = AppSharedPreferences();
  bool isDataLoaded = false;
  bool hasDentalPlan = false;
  var languageID;
  int totalAppointmentTime = 0;

  List<DoctorList> doctorsList = [];

  late DentalProceduresModel dentalProceduresModel;
  List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital = [];

  late ProjectViewModel projectViewModel;

  bool isDoctorsList = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) => checkIfHasDentalPlan());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).chiefComplaints,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      isShowDecPage: false,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: Container(
        child: !hasDentalPlan
            ? isDoctorsList
                ? Container(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          ...List.generate(
                            patientDoctorAppointmentListHospital.length,
                            (index) => Padding(
                              padding: const EdgeInsets.all(14.0),
                              child: AppExpandableNotifier(
                                  isExpand: true,
                                  title: patientDoctorAppointmentListHospital[index].filterName! +
                                      " - " +
                                      patientDoctorAppointmentListHospital[index].distanceInKMs! +
                                      " " +
                                      TranslationBase.of(context).km,
                                  bodyWidget: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: patientDoctorAppointmentListHospital[index].patientDoctorAppointmentList!.map((doctor) {
                                      return DoctorView(
                                        doctor: doctor,
                                        isLiveCareAppointment: false,
                                        isContinueDentalPlan: hasDentalPlan,
                                      );
                                    }).toList(),
                                  )),
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                : ListView.separated(
                    itemCount: complaintsList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        child: DentalComplaintCard(
                          listDentalChiefComplain: complaintsList[index],
                          languageID: languageID,
                          isDoctorNameSearch: widget.isDoctorNameSearch,
                          onSelectedMethod: widget.onSelectedMethod,
                          isFromHospitalSearchPage: widget.isFromHospitalSearchPage,
                          onDoctorFetched: widget.isFromHospitalSearchPage
                              ? (doctorsList) {
                                  if (doctorsList.registeredDoctorMap?.isNotEmpty == true) {
                                    Navigator.pop(context, doctorsList);
                                  } else {
                                    Utils.showErrorToast(TranslationBase.of(context).noDataAvailable);
                                  }
                                }
                              : null,
                        )..logAnalytics = () {
                            final info = widget.searchInfo;
                            locator<GAnalytics>()
                                .appointment
                                .book_appointment_chief_complaints(appointment_type: 'regular', hospital: info.hospital, clinic: info.clinic, treatment: complaintsList[index]);
                          },
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) {
                      return Padding(
                        padding: const EdgeInsets.only(left: 14, right: 14),
                        child: mDivider(CustomColors.devider),
                      );
                    },
                  )
            : Container(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 12.0, left: 12.0, right: 12.0),
                        child: Text(TranslationBase.of(context).dentalProcedureList, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, letterSpacing: -0.46)),
                      ),
                      Container(
                        decoration: cardRadius(10),
                        margin: EdgeInsets.all(12.0),
                        child: Table(
                          children: getProceduresData(),
                        ),
                      ),
                      ...List.generate(
                        patientDoctorAppointmentListHospital.length,
                        (index) => AppExpandableNotifier(
                            isExpand: true,
                            title: patientDoctorAppointmentListHospital[index].filterName! + " - " + patientDoctorAppointmentListHospital[index].distanceInKMs! + " " + TranslationBase.of(context).km,
                            bodyWidget: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: patientDoctorAppointmentListHospital[index].patientDoctorAppointmentList!.map((doctor) {
                                return DoctorView(
                                  doctor: doctor,
                                  isLiveCareAppointment: false,
                                  isContinueDentalPlan: hasDentalPlan,
                                );
                              }).toList(),
                            )),
                      )
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  getLanguageID() async {
    languageID = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
  }

  checkIfHasDentalPlan() {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.checkIfHasDentalPlan(widget.searchInfo!.ProjectID!, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        if (res['List_IsPatientHasOnGoingEstimation'].length != 0) {
          ConfirmDialog dialog = new ConfirmDialog(
              context: context,
              confirmMessage: TranslationBase.of(context).continuePlan,
              okText: TranslationBase.of(context).yes,
              cancelText: TranslationBase.of(context).no,
              okFunction: () => {Navigator.of(context).pop(), continueDentalPlan(), hasDentalPlan = true},
              cancelFunction: () => {getChiefComplaintsList(), hasDentalPlan = false});
          dialog.showAlertDialog(context);
        } else {
          getChiefComplaintsList();
        }
      }
    }).catchError((err) {
      print(err);
    });
  }

  List<TableRow> getProceduresData() {
    List<TableRow> tableRow = [];

    tableRow.add(
      TableRow(
        children: [
          Container(
            child: Container(
              margin: EdgeInsets.all(12.0),
              child: Text(TranslationBase.of(context).procedureName, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
            ),
          ),
          Container(
            child: Container(
              margin: EdgeInsets.all(12.0),
              child: Text(TranslationBase.of(context).timeNeeded, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
            ),
          ),
        ],
      ),
    );
    dentalProceduresModel.listIsPatientHasOnGoingEstimation!.forEach((procedure) {
      tableRow.add(TableRow(children: [
        Container(
          margin: EdgeInsets.all(12.0),
          child: Text(procedure!.procedureName!, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
        ),
        Container(
          margin: EdgeInsets.all(12.0),
          child: Text(procedure.neededTime.toString() + " " + TranslationBase.of(context).minute, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
        ),
      ]));
    });
    tableRow.add(
      TableRow(
        children: [
          Container(
            margin: EdgeInsets.all(12.0),
            child: Text(TranslationBase.of(context).totalTimeNeeded, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
          ),
          Container(
            margin: EdgeInsets.all(12.0),
            child: Text(totalAppointmentTime.toString() + " " + TranslationBase.of(context).minute, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.46)),
          ),
        ],
      ),
    );
    return tableRow;
  }

  continueDentalPlan() {
    int languageID = projectViewModel.isArabic ? 1 : 2;
    DoctorsListService service = new DoctorsListService();

    GifLoaderDialogUtils.showMyDialog(context);
    int appoTime = 0;
    service.getDoctorsList(int.parse("17"), widget.searchInfo!.ProjectID!, false, languageID, context, isContinueDentalPlan: true).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        dentalProceduresModel = DentalProceduresModel.fromJson(res as Map<String, dynamic>);
        //Changed by Aamir added Map into string dynamic
        dentalProceduresModel.listIsPatientHasOnGoingEstimation!.forEach((procedure) {
          appoTime += procedure!.neededTime!;
        });
        setState(() {
          hasDentalPlan = true;
          totalAppointmentTime = appoTime;
        });

        if (res['DoctorList'].length != 0) {
          doctorsList.clear();
          res['DoctorList'].forEach((v) {
            doctorsList.add(new DoctorList.fromJson(v));
          });
          doctorsList.forEach((element) {
            List<PatientDoctorAppointmentList> doctorByHospital = patientDoctorAppointmentListHospital
                .where(
                  (elementClinic) => elementClinic.filterName == element.projectName,
                )
                .toList();

            if (doctorByHospital.length != 0) {
              patientDoctorAppointmentListHospital[patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
            } else {
              patientDoctorAppointmentListHospital.add(PatientDoctorAppointmentList(
                  filterName: element.projectName,
                  distanceInKMs: element.projectDistanceInKiloMeters.toString(),
                  projectTopName: element.projectTopName,
                  projectBottomName: element.projectBottomName,
                  patientDoctorAppointment: element));
            }
          });
        } else {}
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
  }

  getChiefComplaintsList() {
    int languageID = projectViewModel.isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    getLanguageID();
    hasDentalPlan = false;
    ClinicListService service = new ClinicListService();
    int? patientID = projectViewModel.isLogin ? projectViewModel.user.patientID : -1;
    service.getChiefComplaintsList(patientID!, widget.searchInfo.ClinicID!, widget.searchInfo.ProjectID!, languageID, false, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorList'].length != 0) {
            isDoctorsList = true;
            doctorsList.clear();
            res['DoctorList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
            });
            doctorsList.forEach((element) {
              List<PatientDoctorAppointmentList> doctorByHospital = patientDoctorAppointmentListHospital
                  .where(
                    (elementClinic) => elementClinic.filterName == element.projectName,
                  )
                  .toList();

              if (doctorByHospital.length != 0) {
                patientDoctorAppointmentListHospital[patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
              } else {
                patientDoctorAppointmentListHospital.add(PatientDoctorAppointmentList(
                    filterName: element.projectName,
                    distanceInKMs: element.projectDistanceInKiloMeters.toString(),
                    projectTopName: element.projectTopName,
                    projectBottomName: element.projectBottomName,
                    patientDoctorAppointment: element));
              }
            });
          } else {
            isDoctorsList = false;
            res['List_DentalChiefComplain'].forEach((v) {
              complaintsList.add(new ListDentalChiefComplain.fromJson(v));
            });
          }
        });
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
