import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/models/header_model.dart';
import 'package:diplomaticquarterapp/routes.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/date_uitl.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/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/new_design/doctor_header.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import 'book_reminder_page.dart';
import 'components/DocAvailableAppointments.dart';

class BookConfirm extends StatefulWidget {
  DoctorList doctor;
  String selectedDate;
  String selectedTime;

  String appoDateFormatted = "";
  String appoTimeFormatted = "";
  bool isLiveCareAppointment;
  int initialSlotDuration;

  BookConfirm({@required this.doctor, @required this.selectedDate, @required this.isLiveCareAppointment, @required this.selectedTime, @required this.initialSlotDuration});

  DoctorsListService service;
  PatientShareResponse patientShareResponse;

  // AuthenticatedUser authUser;

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

class _BookConfirmState extends State<BookConfirm> {
  ProjectViewModel projectViewModel;
  ToDoCountProviderModel toDoProvider;

  AppSharedPreferences sharedPref = new AppSharedPreferences();

  @override
  void initState() {
    // widget.authUser = new AuthenticatedUser();
    // getPatientData();
    widget.service = new DoctorsListService();
    widget.patientShareResponse = new PatientShareResponse();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: widget.doctor.doctorTitle + " " + widget.doctor.name,
      isShowDecPage: false,
      isShowAppBar: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            DoctorHeader(
              headerModel: HeaderModel(
                widget.doctor.name,
                widget.doctor.doctorID,
                widget.doctor.doctorImageURL,
                widget.doctor.speciality,
                "",
                widget.doctor.projectName,
                null,
                null,
                widget.doctor.nationalityFlagURL,
                widget.doctor.doctorRate,
                null,
                widget.doctor.noOfPatientsRate,
                "",
              ),
              isNeedToShowButton: false,
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    TranslationBase.of(context).confirmAppoHeading,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 16.0,
                      letterSpacing: -0.64,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  mHeight(20),
                  Container(
                    decoration: cardRadius(12),
                    margin: EdgeInsets.zero,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(16, 20, 16, 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            TranslationBase.of(context).appoInfo,
                            style: TextStyle(
                              fontSize: 14.0,
                              color: Colors.black,
                              letterSpacing: -0.36,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          mHeight(16),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.max,
                            children: <Widget>[
                              if (!widget.isLiveCareAppointment) showInfo(TranslationBase.of(context).hospital, widget.doctor.projectName),
                              showInfo(TranslationBase.of(context).clinic, widget.doctor.clinicName),
                              showInfo(TranslationBase.of(context).date, getDate()),
                              showInfo(TranslationBase.of(context).time, widget.selectedTime)
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  mHeight(12),
                  Container(
                    decoration: cardRadius(12),
                    margin: EdgeInsets.zero,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(16, 20, 16, 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            TranslationBase.of(context).patientInfo,
                            style: TextStyle(
                              fontSize: 14.0,
                              color: Colors.black,
                              letterSpacing: -0.36,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          mHeight(16),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.max,
                            children: <Widget>[
                              showInfo(TranslationBase.of(context).name, projectViewModel.user.firstName + " " + projectViewModel.user.lastName),
                              showInfo(TranslationBase.of(context).gender, projectViewModel.user.genderDescription),
                              showInfo(TranslationBase.of(context).age, projectViewModel.user.age.toString())
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 120.0,
            ),
          ],
        ),
      ),
      bottomSheet: Container(
        color: CustomColors.appBackgroudGreyColor,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: 45.0,
          margin: EdgeInsets.all(16),
          child: ButtonTheme(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            minWidth: MediaQuery.of(context).size.width * 0.7,
            height: 40.0,
            child: CustomTextButton(
              backgroundColor: CustomColors.green,
              disabledForegroundColor: new Color(0xFFbcc2c4).withOpacity(0.38),
              disabledBackgroundColor: new Color(0xFFbcc2c4).withOpacity(0.12),
              elevation: 0,
              onPressed: () async {
                bool isLiveCareSchedule = await this.sharedPref.getBool(IS_LIVECARE_APPOINTMENT);
                if (isLiveCareSchedule != null && isLiveCareSchedule) {
                  insertLiveCareScheduledAppointment(context, widget.doctor);
                } else {
                  insertAppointment(context, widget.doctor, widget.initialSlotDuration);
                }
              },
              child: Text(TranslationBase.of(context).bookAppo, style: TextStyle(fontSize: 16.0, letterSpacing: -0.48, color: Colors.white)),
            ),
          ),
        ),
      ),
    );
  }

  Widget showInfo(String title, String des) {
    return Container(
      child: Row(
        children: [
          Text(
            title + ": ",
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Color(0xFF575757),
              letterSpacing: -0.4,
            ),
          ),
          Text(
            des,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Colors.black,
              letterSpacing: -0.48,
            ),
          ),
        ],
      ),
    );
  }

  cancelAppointment(DoctorList docObject, AppoitmentAllHistoryResultList appo, BuildContext context) async {
    ConfirmDialog.closeAlertDialog(context);
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    bool isLiveCareSchedule = await this.sharedPref.getBool(IS_LIVECARE_APPOINTMENT);
    service.cancelAppointment(appo, context, isReschedule: true).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        Future.delayed(new Duration(milliseconds: 1500), () async {
          if (isLiveCareSchedule != null && isLiveCareSchedule) {
            insertLiveCareScheduledAppointment(context, widget.doctor);
          } else {
            insertAppointment(context, widget.doctor, widget.initialSlotDuration);
          }
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  insertAppointment(context, DoctorList docObject, int initialSlotDuration) {
    final timeSlot = DocAvailableAppointments.selectedAppoDateTime;

    GifLoaderDialogUtils.showMyDialog(context);
    AppoitmentAllHistoryResultList appo;
    widget.service
        .insertAppointment(docObject.doctorID, docObject.clinicID, docObject.projectID, widget.selectedTime, widget.selectedDate, initialSlotDuration, context, null, null, null, projectViewModel)
        .then((res) {
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: TranslationBase.of(context).bookedSuccess);

        Future.delayed(new Duration(milliseconds: 500), () {
          getPatientShare(context, res['AppointmentNo'], docObject.clinicID, docObject.projectID, docObject);
          getToDoCount();
        });
        projectViewModel.analytics.appointment.book_appointment_confirmation_success(appointment_type: 'regular', dateTime: timeSlot, doctor: widget.doctor);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        appo = new AppoitmentAllHistoryResultList();
        appo.appointmentNo = res['SameClinicApptList'][0]['AppointmentNo'];
        appo.clinicID = res['SameClinicApptList'][0]['DoctorID'];
        appo.projectID = res['SameClinicApptList'][0]['ProjectID'];
        appo.endTime = res['SameClinicApptList'][0]['EndTime'];
        appo.startTime = res['SameClinicApptList'][0]['StartTime'];
        appo.doctorID = res['SameClinicApptList'][0]['DoctorID'];
        appo.isLiveCareAppointment = false;
        appo.originalClinicID = 0;
        appo.originalProjectID = 0;
        appo.appointmentDate = res['SameClinicApptList'][0]['AppointmentDate'];

        ConfirmDialog dialog = new ConfirmDialog(
            context: context,
            confirmMessage: res['ErrorEndUserMessage'],
            okText: TranslationBase.of(context).confirm,
            cancelText: TranslationBase.of(context).cancel_nocaps,
            okFunction: () => {cancelAppointment(docObject, appo, context)},
            cancelFunction: () => {});
        dialog.showAlertDialog(context);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
    projectViewModel.analytics.appointment.book_appointment_click_confirm(appointment_type: 'regular', dateTime: timeSlot, doctor: widget.doctor);
  }

  insertLiveCareScheduledAppointment(context, DoctorList docObject) {
    final timeSlot = DocAvailableAppointments.selectedAppoDateTime;
    widget.selectedDate = timeSlot.toUtc().add(Duration(hours: 3)).toString().split(" ")[0];
    widget.selectedTime = timeSlot.toUtc().add(Duration(hours: 3)).toString().split(" ")[1].substring(0, 5);
    GifLoaderDialogUtils.showMyDialog(context);
    AppoitmentAllHistoryResultList appo;
    widget.service.insertLiveCareScheduleAppointment(docObject.doctorID, docObject.clinicID, docObject.projectID, docObject.serviceID, widget.selectedTime, widget.selectedDate, context).then((res) {
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: TranslationBase.of(context).bookedSuccess);
        print(res['AppointmentNo']);

        Future.delayed(new Duration(milliseconds: 500), () {
          getLiveCareAppointmentPatientShare(context, res['AppointmentNo'], docObject.clinicID, docObject.projectID, docObject);
          getToDoCount();
        });
        projectViewModel.analytics.appointment.book_appointment_confirmation_success(appointment_type: 'livecare', dateTime: timeSlot, doctor: widget.doctor);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        appo = new AppoitmentAllHistoryResultList();
        appo.appointmentNo = res['SameClinicApptList'][0]['AppointmentNo'];
        appo.clinicID = res['SameClinicApptList'][0]['DoctorID'];
        appo.projectID = res['SameClinicApptList'][0]['ProjectID'];
        appo.endTime = res['SameClinicApptList'][0]['EndTime'];
        appo.startTime = res['SameClinicApptList'][0]['StartTime'];
        appo.doctorID = res['SameClinicApptList'][0]['DoctorID'];
        appo.isLiveCareAppointment = true;
        appo.originalClinicID = 0;
        appo.originalProjectID = 0;
        appo.appointmentDate = res['SameClinicApptList'][0]['AppointmentDate'];

        ConfirmDialog dialog = new ConfirmDialog(
            context: context,
            confirmMessage: res['ErrorEndUserMessage'],
            okText: TranslationBase.of(context).confirm,
            cancelText: TranslationBase.of(context).cancel_nocaps,
            okFunction: () => {cancelAppointment(docObject, appo, context)},
            cancelFunction: () => {});
        dialog.showAlertDialog(context);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });

    projectViewModel.analytics.appointment.book_appointment_click_confirm(appointment_type: 'livecare', dateTime: timeSlot, doctor: widget.doctor);
  }

  getToDoCount() {
    toDoProvider.setState(0, true, toDoProvider.notificationsCount);
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      print(res['AppointmentActiveNumber']);
      if (res['MessageStatus'] == 1) {
        toDoProvider.setState(res['AppointmentActiveNumber'], true, toDoProvider.notificationsCount);
      } else {}
    }).catchError((err) {
      print(err);
    });
  }

  getPatientShare(context, String appointmentNo, int clinicID, int projectID, DoctorList docObject) {
    widget.service.getPatientShare(appointmentNo, clinicID, projectID, context).then((res) {
      projectViewModel.selectedBodyPartList.clear();
      projectViewModel.laserSelectionDuration = 0;
      print(res);
      widget.patientShareResponse = new PatientShareResponse.fromJson(res);
      navigateToBookSuccess(context, docObject, widget.patientShareResponse);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      // AppToast.showErrorToast(message: err);
      projectViewModel.selectedBodyPartList.clear();
      projectViewModel.laserSelectionDuration = 0;
      navigateToHome(context);
      print(err);
    });
  }

  getLiveCareAppointmentPatientShare(context, String appointmentNo, int clinicID, int projectID, DoctorList docObject) {
    widget.service.getLiveCareAppointmentPatientShare(appointmentNo, clinicID, projectID, context).then((res) {
      widget.patientShareResponse = new PatientShareResponse.fromJson(res);
      GifLoaderDialogUtils.hideDialog(context);
      navigateToBookSuccess(context, docObject, widget.patientShareResponse);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      navigateToHome(context);
      print(err);
    });
  }

  String getTime(DateTime dateTime) {
    final DateFormat formatter = DateFormat('HH:mm');
    setState(() {
      widget.appoTimeFormatted = formatter.format(dateTime);
      print(widget.appoTimeFormatted);
    });
    return widget.appoTimeFormatted;
  }

  String getDate() {
    var dateObj = new DateTime(int.parse(widget.selectedDate.split("-")[0]), int.parse(widget.selectedDate.split("-")[1]), int.parse(widget.selectedDate.split("-")[2]), 0, 0, 0, 0);

    setState(() {
      widget.appoDateFormatted = DateUtil.getWeekDay(dateObj.weekday) + ", " + dateObj.day.toString() + " " + DateUtil.getMonth(dateObj.month) + " " + dateObj.year.toString();
    });

    return DateUtil.getDayMonthYearDateFormatted(dateObj);
  }

  DateTime getDateTime() {
    var parts = widget.selectedTime.split(':');

    try {
      var dateObj = new DateTime(int.parse(widget.selectedDate.split("-")[0]), int.parse(widget.selectedDate.split("-")[1]), int.parse(widget.selectedDate.split("-")[2]), int.parse(parts[0].trim()),
          int.parse(parts[1].trim()), 0, 0);
      return dateObj;
    } catch (e) {
      var dateObj = new DateTime(int.parse(widget.selectedDate.split("-")[0]), int.parse(widget.selectedDate.split("-")[1]), int.parse(widget.selectedDate.split("-")[2]), 0, 0, 0, 0);
      return dateObj;
    }
  }

  String getDoctorSpeciality(List<String> docSpecial) {
    String docSpeciality = "";
    docSpecial.forEach((v) {
      docSpeciality = docSpeciality + v + "\n";
    });
    return docSpeciality;
  }

  // getPatientData() async {
  //   AppSharedPreferences sharedPref = AppSharedPreferences();
  //   if (await sharedPref.getObject(USER_PROFILE) != null) {
  //     var data = AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
  //     setState(() {
  //       print(data);
  //       widget.authUser = data;
  //     });
  //   }
  // }

  Future navigateToHome(context) async {
    Navigator.of(context).popAndPushNamed(HOME);
  }

  Future navigateToBookSuccess(context, DoctorList docObject, PatientShareResponse patientShareResponse) async {
    GifLoaderDialogUtils.hideDialog(context);
    this.sharedPref.remove(IS_LIVECARE_APPOINTMENT);
    Navigator.push(
      context,
      FadePage(
        page: BookReminderPage(
          docObject: docObject,
          patientShareResponse: patientShareResponse,
          appoDateFormatted: widget.appoDateFormatted,
          appoTimeFormatted: widget.selectedTime,
          dateTime: getDateTime(),
        ),
      ),
    );
  }
}
