import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorProfile.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorRateDetails.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/doctor_post_pre_images_page.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/robo_search/event_provider.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_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_material_pickers/flutter_material_pickers.dart';
import 'package:rating_bar/rating_bar.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;

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

  AuthenticatedUser authUser;

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

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

  AppSharedPreferences sharedPref = AppSharedPreferences();

  List<DoctorRateDetails> doctorDetailsList = List();

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

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).bookAppo,
      isShowAppBar: true,
      isShowDecPage: false,
      bottomSheet: showFooterButton
          ? Container(
              width: MediaQuery.of(context).size.width,
              height: 50.0,
              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: 45.0,
                child: RaisedButton(
                  color: new Color(0xFF60686b),
                  textColor: Colors.white,
                  disabledTextColor: Colors.white,
                  disabledColor: new Color(0xFFbcc2c4),
                  onPressed: goToBookConfirm,
                  child: Text(TranslationBase.of(context).bookNow,
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
            )
          : null,
      body: Container(
        color: new Color(0xFFf6f6f6),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                color: Colors.white,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          alignment: Alignment.center,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(100.0),
                            child: Image.network(widget.doctor.doctorImageURL,
                                fit: BoxFit.fill, height: 120.0, width: 120.0),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          alignment: Alignment.center,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(100.0),
                            child: Image.asset('assets/images/drSchedul.png'),
                          ),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      alignment: Alignment.center,
                      child: Text(
                          widget.doctor.doctorTitle + " " + widget.doctor.name,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontSize: 20.0,
                              color: Colors.grey[900],
                              letterSpacing: 1.0)),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      alignment: Alignment.center,
                      child: Text(widget.doctor.projectName,
                          style: TextStyle(
                              fontSize: 15.0,
                              color: Colors.grey[900],
                              letterSpacing: 1.0)),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      alignment: Alignment.center,
                      child: Text(widget.doctor.clinicName,
                          style: TextStyle(
                              fontSize: 13.0,
                              color: Colors.grey[900],
                              letterSpacing: 1.0)),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5.0),
                      alignment: Alignment.center,
                      child: RatingBar.readOnly(
                        initialRating:
                            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,
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        getDoctorRatingsDetails();
                      },
                      child: Container(
                        margin: EdgeInsets.only(top: 5.0),
                        alignment: Alignment.center,
                        child: Text(
                            "(" +
                                widget.docProfileList.noOfPatientsRate
                                    .toString() +
                                " " +
                                TranslationBase.of(context).reviews +
                                ")",
                            style: TextStyle(
                              fontSize: 14.0,
                              color: Colors.blue[800],
                              letterSpacing: 1.0,
                              decoration: TextDecoration.underline,
                            )),
                      ),
                    ),
                    if (widget.docProfileList.isDoctorHasPrePostImages == true)
                      Container(
                          height: 50,
                          alignment: Alignment.center,
                          child: prePostImagesButton(context)),
                    Container(
                      child: Divider(
                        color: Colors.grey[500],
                      ),
                    ),
                    TabBar(
                      onTap: (index) {
                        setState(() {
                          index == 1
                              ? showFooterButton = true
                              : showFooterButton = false;
                          print(showFooterButton);
                        });
                      },
                      tabs: [
                        Tab(
                            child: Text(TranslationBase.of(context).docInfo,
                                style: TextStyle(color: Colors.black))),
                        Tab(
                          child: Text(TranslationBase.of(context).availableAppo,
                              style: TextStyle(color: Colors.black)),
                        )
                      ],
                      controller: _tabController,
                    ),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height,
                child: TabBarView(
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                    DoctorInformation(docProfileList: widget.docProfileList),
                    DocAvailableAppointments(
                        doctor: widget.doctor,
                        isLiveCareAppointment: widget.isLiveCareAppointment)
                  ],
                  controller: _tabController,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget prePostImagesButton(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: MaterialButton(
        height: 50,
        color: Theme.of(context).appBarTheme.color,
        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, 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, 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,
                            ),
                          ),
                          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: RaisedButton(
                                  elevation: 0.0,
                                  color: Colors.white,
                                  textColor: Colors.red,
                                  hoverColor: Colors.transparent,
                                  focusColor: Colors.transparent,
                                  highlightColor: Colors.transparent,
                                  disabledColor: new Color(0xFFbcc2c4),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text(
                                      TranslationBase.of(context).cancel,
                                      style: TextStyle(fontSize: 18.0)),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        transitionDuration: Duration(milliseconds: 500),
        barrierDismissible: true,
        barrierLabel: '',
        context: context,
        pageBuilder: (context, animation1, animation2) {});
  }

  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 (DocAvailableAppointments.areSlotsAvailable) {
      if (await sharedPref.getObject(USER_PROFILE) != null) {
        navigateToBookConfirm(context);
      } 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: "Please select Time Slot to continue");
  }

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