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/DoctorRateDetails.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/BookConfirm.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/components/DocAvailableAppointments.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.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/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/SchedulePage.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rating_bar/rating_bar.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'widgets/AppointmentActions.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';

class AppointmentDetails extends StatefulWidget {
  AppoitmentAllHistoryResultList appo;
  static bool isLoading = false;
  final dynamic doctorSchedule;
  static bool showFooterButton = false;

  AppointmentDetails({@required this.appo, this.doctorSchedule});

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

class _AppointmentDetailsState extends State<AppointmentDetails>
    with SingleTickerProviderStateMixin {
  static TabController _tabController;

  AppSharedPreferences sharedPref = AppSharedPreferences();
  List<DoctorRateDetails> doctorDetailsList = List();

  @override
  void initState() {
    AppointmentDetails.showFooterButton = false;
    if (widget.doctorSchedule != null) {
      _tabController =
          new TabController(length: 2, vsync: this, initialIndex: 1);
      widget.appo.appointmentDate = widget.doctorSchedule['Date'];
    } else {
      _tabController = new TabController(length: 2, vsync: this);
    }
    setTab();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
    AppointmentDetails.showFooterButton = false;
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: widget.appo.doctorNameObj,
      isShowAppBar: true,
      bottomSheet: AppointmentDetails.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: Stack(
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    color: Colors.white,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          alignment: Alignment.center,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(100.0),
                            child: Image.network(widget.appo.doctorImageURL,
                                fit: BoxFit.fill, height: 120.0, width: 120.0),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                              top: 10.0, left: 10.0, right: 10.0),
                          alignment: Alignment.center,
                          child: Text(
                              widget.appo.doctorTitle +
                                  " " +
                                  widget.appo.doctorNameObj,
                              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(
                              getDoctorSpeciality(widget.appo.doctorSpeciality),
                              style: TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.grey[900],
                                  letterSpacing: 1.0)),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 5.0),
                          alignment: Alignment.center,
                          child: RatingBar.readOnly(
                            initialRating:
                                widget.appo.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.appo.noOfPatientsRate.toString() +
                                    " " +
                                    TranslationBase.of(context).reviews +
                                    ")",
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.blue[800],
                                  letterSpacing: 1.0,
                                  decoration: TextDecoration.underline,
                                )),
                          ),
                        ),
                        Container(
                          alignment: Alignment.center,
                          child: Text(
                              DateUtil.getWeekDayMonthDayYearDateFormatted(
                                  DateUtil.convertStringToDate(
                                      widget.appo.appointmentDate),
                                  projectViewModel.isArabic ? "ar" : "en")),
                        ),
                        Container(
                          alignment: Alignment.center,
                          child: Text(widget.appo.startTime.substring(0, 5)),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 10.0),
                          child: Divider(
                            color: Colors.grey[500],
                          ),
                        ),
                        TabBar(
                          onTap: (index) {
                            setState(() {
                              if (index == 1) {
                                if (widget.appo.clinicID == 17 ||
                                    widget.appo.clinicID == 23 ||
                                    widget.appo.isExecludeDoctor) {
                                  _tabController.index =
                                      _tabController.previousIndex;
                                  AppointmentDetails.showFooterButton = false;
                                } else {
                                  AppointmentDetails.showFooterButton = true;
                                }
                              }
                            });
                          },
                          tabs: [
                            Tab(
                                child: Text(
                                    TranslationBase.of(context).appoActions,
                                    style: TextStyle(color: Colors.black))),
                            widget.appo.clinicID == 17 ||
                                    widget.appo.clinicID == 23 ||
                                    widget.appo.isExecludeDoctor
                                ? Tab(
                                    child: Text(
                                        TranslationBase.of(context)
                                            .availableAppo,
                                        style: TextStyle(color: Colors.grey)),
                                  )
                                : Tab(
                                    child: Text(
                                        TranslationBase.of(context)
                                            .availableAppo,
                                        style: TextStyle(color: Colors.black)),
                                  )
                          ],
                          controller: _tabController,
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: MediaQuery.of(context).size.height * 0.87,
                    child: TabBarView(
                      physics: NeverScrollableScrollPhysics(),
                      children: [
                        AppointmentActions(
                            appo: widget.appo,
                            tabController: _tabController,
                            enableFooterButton: enableFooterButton),
                        DocAvailableAppointments(
                            doctor: getDoctorObject(),
                            doctorSchedule: widget.doctorSchedule,
                            isLiveCareAppointment:
                                widget.appo.isLiveCareAppointment)
                      ],
                      controller: _tabController,
                    ),
                  ),
                ],
              ),
              _tabController.index == 1
                  ? Positioned(
                      right: 30.0,
                      //top: 30.0,
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(40),
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 5,
                                blurRadius: 7,
                                offset:
                                    Offset(0, 3), // changes position of shadow
                              ),
                            ]),
                        height: 50,
                        width: 50,
                        margin: EdgeInsets.only(top: 20.0),
                        alignment: Alignment.center,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(100.0),
                          child: IconButton(
                              icon: Image.asset('assets/images/drSchedul.png'),
                              onPressed: () {
                                openSchedule();
                              }),
                        ),
                      ))
                  : SizedBox(),
            ],
          ),
        ),
      ),
    );
  }

  void enableFooterButton() {
    setState(() {
      AppointmentDetails.showFooterButton = true;
    });
  }

  void goToBookConfirm() {
    if (DocAvailableAppointments.areSlotsAvailable)
      navigateToBookConfirm(context);
    else
      AppToast.showErrorToast(message: "Please select Time Slot to continue");
  }

  Future navigateToBookConfirm(context) async {
    Navigator.push(
        context,
        FadePage(
            page: BookConfirm(
                doctor: getDoctorObject(),
                isLiveCareAppointment: widget.appo.isLiveCareAppointment,
                selectedDate: DocAvailableAppointments.selectedDate,
                selectedTime: DocAvailableAppointments.selectedTime)));
  }

  getDoctorRatingsDetails() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsRatingDetails(widget.appo.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);
    });
  }

  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
                                      .appo
                                      .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.appo.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.appo.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.appo.noOfPatientsRate) * 100;
    return width;
  }

  String getDate(String date) {
    DateTime dateObj = DateUtil.convertStringToDate(date);
    return DateUtil.getWeekDay(dateObj.weekday) +
        ", " +
        dateObj.day.toString() +
        " " +
        DateUtil.getMonth(dateObj.month) +
        " " +
        dateObj.year.toString();
  }

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

  DoctorList getDoctorObject() {
    DoctorList docObj = new DoctorList();
    docObj.doctorID = widget.appo.doctorID;
    docObj.clinicID = widget.appo.clinicID;
    docObj.projectID = widget.appo.projectID;
    docObj.doctorTitle = widget.appo.doctorTitle;
    docObj.name = widget.appo.doctorNameObj;
    docObj.clinicName = widget.appo.clinicName;
    docObj.speciality = widget.appo.doctorSpeciality;
    docObj.actualDoctorRate = widget.appo.actualDoctorRate;
    docObj.projectName = widget.appo.projectName;
    docObj.originalClinicID = widget.appo.originalClinicID;
    docObj.doctorImageURL = widget.appo.doctorImageURL;
    return docObj;
  }

  void openSchedule() {
    Navigator.push(
        context,
        FadePage(
            page: SchedulePage(
          appo: widget.appo,
          doctorList: getDoctorObject(),
        )));
  }

  setTab() async {
    var scheduleDoctor = await sharedPref.getObject(DOCTOR_SCHEDULE_DATE_SEL);

    widget.appo.appointmentDate = scheduleDoctor['Date'];
  }
}
