import 'dart:ui';

import 'package:diplomaticquarterapp/core/model/eye/AppoimentAllHistoryResult.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/EyeViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorRateDetails.dart';
import 'package:diplomaticquarterapp/models/header_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/theme/colors.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/dialogs/confirm_send_email_dialog.dart';
import 'package:diplomaticquarterapp/widgets/new_design/doctor_header.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rating_bar/rating_bar.dart';

import 'ClassesPage.dart';
import 'ContactLensPage.dart';

class EyeHomePage extends StatefulWidget {
  final AppoimentAllHistoryResultList appointmentAllHistoryResultList;

  const EyeHomePage({Key key, this.appointmentAllHistoryResultList}) : super(key: key);

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

class _EyeHomePageState extends State<EyeHomePage> with SingleTickerProviderStateMixin {
  TabController _tabController;
  List<DoctorRateDetails> doctorDetailsList = List();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return BaseView<EyeViewModel>(
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        isShowDecPage: false,
        appBarTitle: widget.appointmentAllHistoryResultList.doctorTitle + " " + widget.appointmentAllHistoryResultList.doctorNameObj,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        backgroundColor: CustomColors.appBackgroudGreyColor,
        body: Column(
          children: <Widget>[
            DoctorHeader(
              headerModel: HeaderModel(
                widget.appointmentAllHistoryResultList.doctorTitle + " " + widget.appointmentAllHistoryResultList.doctorNameObj,
                widget.appointmentAllHistoryResultList.doctorID,
                widget.appointmentAllHistoryResultList.doctorImageURL,
                widget.appointmentAllHistoryResultList.doctorSpeciality,
                "",
                widget.appointmentAllHistoryResultList.projectName,
                DateUtil.convertStringToDate(widget.appointmentAllHistoryResultList.appointmentDate),
                widget.appointmentAllHistoryResultList.startTime.substring(0, 5),
                null,
                widget.appointmentAllHistoryResultList.doctorRate,
                widget.appointmentAllHistoryResultList.actualDoctorRate,
                widget.appointmentAllHistoryResultList.noOfPatientsRate,
                "",
                //model.user.emailAddress,
              ),
              isNeedToShowButton: _tabController.index == 0 ? true : projectViewModel.havePrivilege(15),
              showConfirmMessageDialog: true,
              onRatingAndReviewTap: getDoctorRatingsDetails,
              onTap: () {
                showConfirmMessage(context, () async {
                  GifLoaderDialogUtils.showMyDialog(context);
                  await model.sendGlassesPrescriptionEmail(
                      appointmentNo: widget.appointmentAllHistoryResultList.appointmentNo,
                      projectName: widget.appointmentAllHistoryResultList.projectName,
                      projectID: widget.appointmentAllHistoryResultList.projectID);
                  GifLoaderDialogUtils.hideDialog(context);
                }, projectViewModel.user.emailAddress);
              },
            ),
            Container(
              height: 45.0,
              width: double.infinity,
              child: Center(
                child: TabBar(
                  isScrollable: false,
                  controller: _tabController,
                  indicatorWeight: 2.0,
                  indicatorSize: TabBarIndicatorSize.tab,
                  labelColor: Theme.of(context).primaryColor,
                  labelPadding: EdgeInsets.only(top: 4.0, left: 5.0, right: 5.0),
                  unselectedLabelColor: Colors.grey[800],
                  tabs: [
                    Container(
                      // width: double.infinity,
                      child: Center(
                        child: Text(
                          TranslationBase.of(context).classes,
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            // fontSize: 12,
                            letterSpacing: -0.36,
                          ),
                        ),
                      ),
                    ),
                    Container(
                      // width: double.infinity,
                      child: Center(
                        child: Text(
                          TranslationBase.of(context).contactLens,
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            // fontSize: 12,
                            letterSpacing: -0.36,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: TabBarView(
                physics: NeverScrollableScrollPhysics(),
                controller: _tabController,
                children: <Widget>[
                  ClassesPage(
                    glassPerscription: widget.appointmentAllHistoryResultList.listHISGetGlassPerscription[0],
                    appointmentNo: widget.appointmentAllHistoryResultList.appointmentNo,
                    projectName: widget.appointmentAllHistoryResultList.projectName,
                    projectID: widget.appointmentAllHistoryResultList.projectID,
                  ),
                  ContactLensPage(
                    listHISGetContactLensPerscription: widget.appointmentAllHistoryResultList.listHISGetContactLensPerscription[0],
                    appointmentNo: widget.appointmentAllHistoryResultList.appointmentNo,
                    projectName: widget.appointmentAllHistoryResultList.projectName,
                    projectID: widget.appointmentAllHistoryResultList.projectID,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void showConfirmMessage(BuildContext context, GestureTapCallback onTap, String email) {
    showDialog(
      context: context,
      builder: (cxt) => ConfirmSendEmailDialog(
        email: email,
        onTapSendEmail: () {
          onTap();
        },
      ),
    );
  }

  void getDoctorRatingsDetails() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsRatingDetails(widget.appointmentAllHistoryResultList.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.appointmentAllHistoryResultList.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.appointmentAllHistoryResultList.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.appointmentAllHistoryResultList.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.appointmentAllHistoryResultList.noOfPatientsRate) * 100;
    return width;
  }
}
