import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorProfile.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorRateDetails.dart';
import 'package:hmg_patient_app/models/Appointments/SearchInfoModel.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/models/Clinics/ClinicListResponse.dart';
import 'package:hmg_patient_app/models/header_model.dart';
import 'package:hmg_patient_app/pages/BookAppointment/DentalComplaints.dart';
import 'package:hmg_patient_app/pages/BookAppointment/LaserBooking.dart';
import 'package:hmg_patient_app/pages/BookAppointment/components/LaserClinic.dart';
import 'package:hmg_patient_app/pages/BookAppointment/doctor_post_pre_images_page.dart';
import 'package:hmg_patient_app/pages/BookAppointment/waiting_appointment/waiting_appointment_info.dart';
import 'package:hmg_patient_app/pages/MyAppointments/SchedulePage.dart';
import 'package:hmg_patient_app/routes.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/robo_search/event_provider.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_new.dart';
import 'package:hmg_patient_app/widgets/buttons/custom_text_button.dart';
import 'package:hmg_patient_app/widgets/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/new_design/doctor_header.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/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:provider/provider.dart';

import 'BookConfirm.dart';
import 'components/DocAvailableAppointments.dart';
import 'components/DocInfo.dart';

class DoctorProfile extends StatefulWidget {
  DoctorList doctor;
  DoctorProfileList docProfileList;
  final bool isOpenAppt;
  bool isLiveCareAppointment;
  bool isDoctorNameSearch;
  bool isContinueDentalPlan;

  DoctorProfile({required this.doctor, required this.docProfileList, required this.isLiveCareAppointment, this.isOpenAppt = false, this.isDoctorNameSearch = false, this.isContinueDentalPlan = false});

  late AuthenticatedUser authUser;

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

class _DoctorProfileState extends State<DoctorProfile> with TickerProviderStateMixin {
  late TabController _tabController;
  bool showFooterButton = false;
  var event = RobotProvider();
  dynamic doctorSchedule;
  AppSharedPreferences sharedPref = AppSharedPreferences();

  List<DoctorRateDetails> doctorDetailsList = [];

  @override
  void initState() {
    _tabController = new TabController(length: 2, vsync: this, initialIndex: widget.isOpenAppt == true ? 1 : 0);
    _tabController = new TabController(length: 2, vsync: this);
    widget.authUser = new AuthenticatedUser();
    widget.doctor.speciality = widget.docProfileList.specialty;
    getPatientData();
    super.initState();
  }

  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: widget.doctor.doctorTitle! + " " + widget.doctor.name!,
      isShowAppBar: true,
      isShowDecPage: false,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      bottomSheet: showFooterButton
          ? Container(
              color: CustomColors.appBackgroudGreyColor,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: 45.0,
                color: CustomColors.appBackgroudGreyColor,
                margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.width * 0.7,
                  height: 40.0,
                  child: CustomTextButton(
                    backgroundColor: CustomColors.accentColor,
                    elevation: 0,
                    onPressed: goToBookConfirm,
                    child: Text(TranslationBase.of(context).reviewAppointment, style: TextStyle(fontSize: 16.0, letterSpacing: -0.48, color: Colors.white, fontWeight: FontWeight.w600)),
                  ),
                ),
              ),
            )
          : null,
      body: Container(
        color: new Color(0xFFF8F8F8),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            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,
                  widget.doctor.actualDoctorRate!,
                  widget.docProfileList.noOfPatientsRate!,
                  "",
                  decimalDoctorRate: widget.docProfileList.decimalDoctorRate.toString(),
                ),
                buttonIcon: 'assets/images/new/Boo_ Appointment.svg',
                showConfirmMessageDialog: false,
                isNeedToShowButton: !widget.isLiveCareAppointment,
                onTap: () {
                  Navigator.push(
                    context,
                    FadePage(
                      page: SchedulePage(doctorList: widget.doctor),
                    ),
                  ).then((value) {
                    setState(() {
                      if (_tabController.index == 0) {
                        _tabController.animateTo((_tabController.index + 1) % 2);
                        showFooterButton = true;
                      }
                      this.doctorSchedule = value;
                    });
                  });
                  projectViewModel.analytics.appointment.book_appointment_schedule(appointment_type: 'regular', doctor: widget.doctor);
                },
                onRatingAndReviewTap: () {
                  getDoctorRatingsDetails();
                },
                buttonTitle: TranslationBase.of(context).schedule,
              ),
              mDivider(Colors.grey[300]!),
              if (widget.docProfileList.isDoctorHasPrePostImages == true) Container(height: 50, alignment: Alignment.center, child: prePostImagesButton(context)),
              TabBar(
                onTap: (index) {
                  setState(() {
                    if (index == 1) {
                      if (widget.doctor.clinicID == 23 || widget.doctor.clinicID == 47 || widget.isLiveCareAppointment) {
                        _tabController.index = _tabController.previousIndex;
                        showFooterButton = false;
                      } else {
                        showFooterButton = true;
                      }
                    }
                    print(showFooterButton);
                  });
                },
                tabs: [
                  Tab(
                    child: Text(
                      TranslationBase.of(context).docInfo,
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 12,
                        letterSpacing: -0.36,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  Tab(
                    child: Text(
                      TranslationBase.of(context).availableAppo,
                      style: TextStyle(
                        color: widget.isLiveCareAppointment ? Colors.grey : Colors.black,
                        fontSize: 12,
                        letterSpacing: -0.36,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
                controller: _tabController,
              ),
              Container(
                height: MediaQuery.of(context).size.height * 1.5,
                child: TabBarView(
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                    DoctorInformation(docProfileList: widget.docProfileList),
                    DocAvailableAppointments(
                      doctor: widget.doctor,
                      isLiveCareAppointment: widget.isLiveCareAppointment,
                      doctorSchedule: doctorSchedule,
                      isContinueDentalPlan: widget.isContinueDentalPlan,
                    ),
                  ],
                  controller: _tabController,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget prePostImagesButton(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: MaterialButton(
        height: 50,
        color: Theme.of(context).appBarTheme.backgroundColor,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        onPressed: () => openDoctorPrePostImages(),
        child: Text(
          TranslationBase.of(context).beforeAfterImages,
          style: TextStyle(color: Colors.white, fontSize: 15, letterSpacing: 1),
        ),
      ),
    );
  }

  getDoctorRatings() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsRating(widget.doctor.doctorID!, projectViewModel.isArabic ? 1 : 2, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        print(res['NotesDoctorRatingList']);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  getDoctorRatingsDetails() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsRatingDetails(widget.doctor.doctorID!, projectViewModel.isArabic ? 1 : 2, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        doctorDetailsList.clear();
        res['DoctorRatingDetailsList'].forEach((v) {
          doctorDetailsList.add(new DoctorRateDetails.fromJson(v));
        });
        showRatingDialog(doctorDetailsList);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  openDoctorPrePostImages() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService().getDoctorPrePostImages(widget.docProfileList, context).then((images) {
      GifLoaderDialogUtils.hideDialog(context);
      showDialog(
          context: context,
          barrierDismissible: true,
          builder: (ctx) {
            return DoctorPostPreImagesContent(doctorPrePostImages: images);
          });
      // Navigator.push(
      //     context,
      //     FadePage(
      //         page: DoctorPostPreImagesPage(doctorPrePostImages: images,)
      //     )
      // );
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  void showRatingDialog(List<DoctorRateDetails> doctorDetailsList) {
    showGeneralDialog(
        barrierColor: Colors.black.withOpacity(0.5),
        transitionBuilder: (context, a1, a2, widget) {
          final curvedValue = Curves.easeInOutBack.transform(a1.value) - 1.0;
          return Transform(
            transform: Matrix4.translationValues(0.0, curvedValue * 200, 0.0),
            child: Opacity(
              opacity: a1.value,
              child: Dialog(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      // height: 400.0,
                      width: MediaQuery.of(context).size.width * 0.8,
                      color: Colors.white,
                      child: Column(
                        children: [
                          Container(
                              alignment: Alignment.center,
                              width: MediaQuery.of(context).size.width,
                              color: Theme.of(context).primaryColor,
                              margin: EdgeInsets.only(bottom: 5.0),
                              padding: EdgeInsets.all(10.0),
                              child: Text(TranslationBase.of(context).doctorRating, style: TextStyle(fontSize: 22.0, color: Colors.white))),
                          Container(
                              margin: EdgeInsets.only(top: 0.0), child: Text(this.widget.doctor.actualDoctorRate!.ceilToDouble().toString(), style: TextStyle(fontSize: 32.0, color: Colors.black))),
                          Container(
                            margin: EdgeInsets.only(top: 5.0),
                            alignment: Alignment.center,
                            // child: RatingBar.readOnly(
                            //   initialRating: this.widget.doctor.actualDoctorRate!.toDouble(),
                            //   size: 35.0,
                            //   filledColor: Colors.yellow[700],
                            //   emptyColor: Colors.grey[500],
                            //   isHalfAllowed: true,
                            //   halfFilledIcon: Icons.star_half,
                            //   filledIcon: Icons.star,
                            //   emptyIcon: Icons.star,
                            // ),
                            child: RatingBar(
                              itemSize: 20.0,
                              allowHalfRating: true,
                              ignoreGestures: true,
                              initialRating: this.widget.doctor.actualDoctorRate!.toDouble(),
                              ratingWidget: RatingWidget(
                                full: Icon(
                                  Icons.star,
                                  color: CustomColors.accentColor,
                                ),
                                half: Icon(
                                  Icons.star_half,
                                  color: CustomColors.accentColor,
                                ),
                                empty: Icon(
                                  Icons.star_border,
                                  color: CustomColors.accentColor,
                                ),
                              ),
                              onRatingUpdate: (double value) {},
                            ),
                          ),
                          Container(
                              margin: EdgeInsets.only(top: 10.0),
                              child: Text(this.widget.doctor.noOfPatientsRate.toString() + " " + TranslationBase.of(context).reviews, style: TextStyle(fontSize: 14.0, color: Colors.black))),
                          Container(
                            margin: EdgeInsets.only(top: 10.0),
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).excellent, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[0].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Colors.green[700],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).v_good, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[1].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffB7B723),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).good, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[2].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffEBA727),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).average, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[3].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffEB7227),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).below_average, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[4].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffE20C0C),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(margin: EdgeInsets.only(top: 40.0), child: Divider()),
                          Container(
                            margin: EdgeInsets.only(top: 0.0),
                            child: Align(
                              alignment: FractionalOffset.bottomCenter,
                              child: ButtonTheme(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                                minWidth: MediaQuery.of(context).size.width,
                                height: 40.0,
                                child: CustomTextButton(
                                  elevation: 0.0,
                                  backgroundColor: Colors.white,
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text(TranslationBase.of(context).cancel, style: TextStyle(fontSize: 18.0, color: Colors.red)),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        transitionDuration: Duration(milliseconds: 500),
        barrierDismissible: true,
        barrierLabel: '',
        context: context,
        pageBuilder: (context, animation1, animation2) {
          return SizedBox();
        });
  }

  double getRatingWidth(int patientNumber) {
    var width = (patientNumber / this.widget.docProfileList.noOfPatientsRate!) * 100;
    return width;
  }

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

  void goToBookConfirm() async {
    // if (widget.isDoctorNameSearch && widget.doctor.clinicID == 17) {
    //   navigateToDentalComplaints(context);
    // } else {
    if (DocAvailableAppointments.selectedTime == TranslationBase.of(context).waitingAppointment) {
      if (projectViewModel.isLogin) {
        canPayForWalkInAppointment();
      } else {
        ConfirmDialog dialog = new ConfirmDialog(
            context: context,
            confirmMessage: TranslationBase.of(context).loginToUseService,
            okText: TranslationBase.of(context).confirm,
            cancelText: TranslationBase.of(context).cancel_nocaps,
            okFunction: () => {navigateToLogin()},
            cancelFunction: () => {});
        dialog.showAlertDialog(context);
      }
    } else {
      if (DocAvailableAppointments.areSlotsAvailable) {
        if (projectViewModel.isLogin) {
          // if (widget.isDoctorNameSearch && widget.doctor.clinicID == 17 && projectViewModel.user!.age! > 12) {
          if (widget.isDoctorNameSearch && widget.doctor.clinicID == 17) {
            navigateToDentalComplaints(context);
          } else if (widget.isDoctorNameSearch && widget.doctor.clinicID == 253) {
            navigateToLaserClinic(context);
          } else {
            final timeSlot = DocAvailableAppointments.selectedAppoDateTime;
            navigateToBookConfirm(context);
            projectViewModel.analytics.appointment.book_appointment_review(appointment_type: 'regular', dateTime: timeSlot!, doctor: widget.doctor);
          }
        } else {
          ConfirmDialog dialog = new ConfirmDialog(
              context: context,
              confirmMessage: TranslationBase.of(context).loginToUseService,
              okText: TranslationBase.of(context).confirm,
              cancelText: TranslationBase.of(context).cancel_nocaps,
              okFunction: () => {navigateToLogin()},
              cancelFunction: () => {});
          dialog.showAlertDialog(context);
        }
      } else {
        AppToast.showErrorToast(message: TranslationBase.of(context).selectSlot);
      }
    }
  }

  Future navigateToLaserClinic(BuildContext context) async {
    HospitalsModel tempselectedHospital = new HospitalsModel();
    tempselectedHospital.iD = widget.doctor.projectID;
    Navigator.push(
      context,
      FadePage(
        page: LaserClinic(selectedHospital: tempselectedHospital!),
      ),
    );
  }

  Future navigateToDentalComplaints(BuildContext context) async {
    HospitalsModel selectedHospital = new HospitalsModel();
    selectedHospital.name = widget.doctor.projectName;
    ListClinicCentralized selectedClinic = new ListClinicCentralized();
    selectedClinic.clinicDescription = widget.doctor.clinicName;

    SearchInfo searchInfo = new SearchInfo();
    searchInfo.ProjectID = widget.doctor.projectID;
    searchInfo.ClinicID = widget.doctor.clinicID;
    searchInfo.date = DateTime.now();
    searchInfo.hospital = selectedHospital;
    searchInfo.clinic = selectedClinic;

    Navigator.push(
      context,
      FadePage(
        page: DentalComplaints(searchInfo: searchInfo),
      ),
    ).then((value) {
      // setState(() {
      //   dropdownValue = null;
      // });
    });
  }

  navigateToLogin() {
    ConfirmDialog.closeAlertDialog(context);
    Navigator.of(context).pushNamed(
      WELCOME_LOGIN,
    );
  }

  Future navigateToBookConfirm(context) async {
    Navigator.push(
      context,
      FadePage(
        page: BookConfirm(
          doctor: widget.doctor,
          isLiveCareAppointment: widget.isLiveCareAppointment,
          selectedDate: DocAvailableAppointments.selectedDate!,
          selectedTime: DocAvailableAppointments.selectedTime!,
          initialSlotDuration: DocAvailableAppointments.initialSlotDuration!,
          isWalkinAppointment: false,
        ),
      ),
    );
  }

  Future navigateToWaitingAppointment(context) async {
    projectViewModel.setWaitingAppointmentProjectID(widget.doctor.projectID!);
    projectViewModel.setWaitingAppointmentDoctor(widget.doctor);
    Navigator.push(
      context,
      FadePage(
        page: WaitingAppointmentInfo(),
      ),
    );
  }

  canPayForWalkInAppointment() {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.canPayForWalkInAppointment(widget.doctor.clinicID!, widget.doctor.projectID!, widget.doctor.doctorID!).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      navigateToWaitingAppointment(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err, localContext: context);
      print(err);
    });
  }
}
