import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/DentalChiefComplaintsModel.dart';
import 'package:diplomaticquarterapp/models/Appointments/DentalProceduresModel.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/SearchInfoModel.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/DentalComplaintCard.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/widgets/DoctorView.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';

class DentalComplaints extends StatefulWidget {
  SearchInfo searchInfo;

  DentalComplaints({@required this.searchInfo});

  @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 = [];

  DentalProceduresModel dentalProceduresModel;
  List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital = List();

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

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: TranslationBase.of(context).chiefComplaints,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      isShowDecPage: false,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: Container(
        child: !hasDentalPlan
            ? ListView.separated(
                itemCount: complaintsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: DentalComplaintCard(
                      listDentalChiefComplain: complaintsList[index],
                      languageID: languageID,
                    )..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,
                                );
                              }).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()},
              cancelFunction: () => {getChiefComplaintsList()});
          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() {
    DoctorsListService service = new DoctorsListService();

    GifLoaderDialogUtils.showMyDialog(context);
    int appoTime = 0;
    service.getDoctorsList(int.parse("17"), widget.searchInfo.ProjectID, false, context, isContinueDentalPlan: true).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        dentalProceduresModel = DentalProceduresModel.fromJson(res);
        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(), patientDoctorAppointment: element));
            }
          });
        } else {}
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
  }

  getChiefComplaintsList() {
    GifLoaderDialogUtils.showMyDialog(context);
    getLanguageID();
    ClinicListService service = new ClinicListService();
    service.getChiefComplaintsList(widget.searchInfo.ClinicID, widget.searchInfo.ProjectID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          res['List_DentalChiefComplain'].forEach((v) {
            complaintsList.add(new ListDentalChiefComplain.fromJson(v));
          });
        });
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
