import 'package:diplomaticquarterapp/config/shared_pref_kay.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/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/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: "Symptoms",
      body: Container(
        margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
        child: !hasDentalPlan
            ? ListView.builder(
                itemCount: complaintsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    margin: EdgeInsets.only(bottom: 10.0),
                    child: DentalComplaintCard(
                      listDentalChiefComplain: complaintsList[index],
                      languageID: languageID,
                    ),
                  );
                },
              )
            : Container(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 10.0),
                        child: Text(TranslationBase.of(context).dentalProcedureList, textAlign: TextAlign.center, style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold, letterSpacing: 0.5)),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 20.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(),
                            )),
                      )
                    ],
                  ),
                ),
              ),
      ),
    );
  }

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

    tableRow.add(
      TableRow(
        children: [
          Container(
            child: Container(
              child: Center(
                child: Text(TranslationBase.of(context).procedureName, style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14.0)),
              ),
            ),
          ),
          Container(
            child: Container(
              margin: EdgeInsets.only(bottom: 10.0),
              child: Center(
                child: Text(TranslationBase.of(context).timeNeeded, style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14.0)),
              ),
            ),
          ),
        ],
      ),
    );
    dentalProceduresModel.listIsPatientHasOnGoingEstimation.forEach((procedure) {
      tableRow.add(TableRow(children: [
        Container(
          child: Container(
            child: Center(
              child: Text(procedure.procedureName, textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontSize: 14.0)),
            ),
          ),
        ),
        Container(
          child: Container(
            child: Center(
              child: Text(procedure.neededTime.toString() + " mins", textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontSize: 14.0)),
            ),
          ),
        ),
      ]));
    });
    tableRow.add(
      TableRow(
        children: [
          Container(
            child: Container(
              child: Center(
                child: Text(TranslationBase.of(context).totalTimeNeeded, textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14.0)),
              ),
            ),
          ),
          Container(
            child: Container(
              margin: EdgeInsets.only(bottom: 10.0),
              child: Center(
                child: Text(totalAppointmentTime.toString() + " mins", textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14.0)),
              ),
            ),
          ),
        ],
      ),
    );
    return tableRow;
  }

  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);
    });
  }

  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) {
        print(res['List_IsPatientHasOnGoingEstimation']);
        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));
          });
          print(complaintsList.length);
        });
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
