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/OBGyneProcedureListResponse.dart';
import 'package:hmg_patient_app/models/Appointments/SearchInfoModel.dart';
import 'package:hmg_patient_app/models/Clinics/ClinicListResponse.dart';
import 'package:hmg_patient_app/pages/BookAppointment/DentalComplaints.dart';
import 'package:hmg_patient_app/pages/ToDoList/ObGyne/ObGyne-TimeSlots.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.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/widgets/avatar/large_avatar.dart';
import 'package:hmg_patient_app/widgets/dragable_sheet.dart';
import 'package:hmg_patient_app/widgets/my_rich_text.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 '../DoctorProfile.dart';

class DoctorView extends StatefulWidget {
  final DoctorList doctor;
  bool? isLiveCareAppointment;
  bool isObGyneAppointment;
  bool isShowFlag;
  bool isDoctorNameSearch;
  bool isContinueDentalPlan;
  OBGyneProcedureListResponse? obGyneProcedureListResponse;
  final VoidCallback? onTap;
  bool isShowDate;

  DoctorView(
      {required this.doctor,
      this.isLiveCareAppointment,
      this.isObGyneAppointment = false,
      this.isDoctorNameSearch = false,
      this.isContinueDentalPlan = false,
      this.isShowFlag = true,
      this.isShowDate = true,
      this.onTap,
      this.obGyneProcedureListResponse});

  @override
  State<DoctorView> createState() => _DoctorViewState();
}

class _DoctorViewState extends State<DoctorView> {
  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return InkWell(
      onTap: () {
        if (widget.isObGyneAppointment) {
          next(context);
        } else {
          // if (doctor.clinicID == 17 && isDoctorNameSearch) {
          //   showDentalChiefComplaintsList(context);
          // } else
          if (widget.isShowFlag) {
            getDoctorsProfile(context, widget.doctor, isAppo: true, isContinueDentalPlan: widget.isContinueDentalPlan);
          }
          (widget.onTap ?? () {})(); // For log analytics of doctor click from book appointment
        }
      },
      child: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
            boxShadow: [
              BoxShadow(
                color: Color(0xff000000).withOpacity(.05),
                //spreadRadius: 5,
                blurRadius: 5,
                offset: Offset(0, -3),
              ),
            ],
            color: Colors.white),
        child: Padding(
          padding: const EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 12),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      widget.doctor.name ?? "",
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64, height: 25 / 16),
                    ),
                  ),
                  // widget.isShowDate
                  //     ? Text(
                  //         DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(widget.doctor.date)),
                  //         style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0xff2B353E), letterSpacing: -0.48, height: 18 / 12),
                  //       )
                  //     : Container(),
                ],
              ),
              if (widget.doctor.doctorTitle != null) SizedBox(height: 6),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  LargeAvatar(
                    name: widget.doctor.name ?? "",
                    url: widget.doctor.doctorImageURL!,
                    width: 48,
                    height: 48,
                  ),
                  SizedBox(width: 11),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        if (widget.doctor.clinicName != null) MyRichText(TranslationBase.of(context).clinic + ":", widget.doctor.clinicName!, context.read<ProjectViewModel>().isArabic),
                        if (widget.doctor.projectName != null) MyRichText(TranslationBase.of(context).branch, widget.doctor.projectName!, context.read<ProjectViewModel>().isArabic),
                        if (!projectViewModel.isArabic)
                          if (widget.doctor.speciality != null && widget.doctor.speciality!.length > 0)
                            Text(
                              this.widget.doctor.speciality![0].trim(),
                              // getDoctorSpeciality(this.doctor.speciality).trim(),
                              style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.48, height: 18 / 12),
                            ),
                        if (projectViewModel.isArabic)
                          if (widget.doctor.specialityN != null && widget.doctor.specialityN!.length > 0)
                            Text(
                              this.widget.doctor.specialityN![0].trim(),
                              // getDoctorSpeciality(this.doctor.speciality).trim(),
                              style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.48, height: 18 / 12),
                            ),
                        if (widget.doctor.nearestFreeSlot != null)
                          Text(
                            getDate(widget.doctor.nearestFreeSlot),
                            style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff359846), letterSpacing: -0.48, height: 18 / 12),
                          ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.max,
                          children: <Widget>[
                            //changed By Aamir
                            RatingBar(
                              initialRating: 3,
                              direction: Axis.horizontal,
                              allowHalfRating: true,
                              itemCount: 5,
                              itemSize: 20,
                              ignoreGestures: true,
                              ratingWidget: RatingWidget(
                                full: Icon(
                                  Icons.star,
                                  color: CustomColors.accentColor,
                                ),
                                half: Icon(
                                  Icons.star_half,
                                  color: CustomColors.accentColor,
                                ),
                                empty: Icon(
                                  Icons.star,
                                  color: CustomColors.accentColor,
                                ),
                              ),
                              tapOnlyMode: true,
                              itemPadding: EdgeInsets.symmetric(horizontal: 4.0),
                              unratedColor: Colors.grey[500],
                              onRatingUpdate: (rating) {
                                print(rating);
                              },
                            ),
                            // RatingBar.readOnly(
                            //   initialRating: this.doctor.actualDoctorRate!.toDouble(),
                            //   size: 16.0,
                            //   filledColor: Color(0XFFD02127),
                            //   emptyColor: Color(0XFFD02127),
                            //   isHalfAllowed: true,
                            //   halfFilledIcon: Icons.star_half,
                            //   filledIcon: Icons.star,
                            //   emptyIcon: Icons.star_border,
                            // ),
                            if (widget.isShowFlag)
                              Icon(
                                Icons.arrow_forward,
                                color: Theme.of(context).primaryColor,
                              ),
                            //   if (isShowFlag) Image.network(this.doctor.nationalityFlagURL, width: 22.0, height: 22.0)
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  showDentalChiefComplaintsList(BuildContext context) {
    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;

    showDraggableDialog(
        context,
        DentalComplaints(
            isDoctorNameSearch: true,
            onSelectedMethod: () {
              Navigator.pop(context);
            },
            searchInfo: searchInfo));
  }

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

  getDoctorsProfile(context, DoctorList docObject, {isAppo, bool isContinueDentalPlan = false}) {
    int languageID = projectViewModel.isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    List<DoctorProfileList> docProfileList = [];
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsProfile(docObject.doctorID!, docObject.clinicID!, docObject!.projectID!, languageID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        if (res['DoctorProfileList'].length != 0) {
          res['DoctorProfileList'].forEach((v) {
            docProfileList.add(new DoctorProfileList.fromJson(v));
          });
        } else {}
        navigateToDoctorProfile(context, docObject, docProfileList[0], isAppo: isAppo, isContinueDentalPlan: isContinueDentalPlan);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err, localContext: context);
      print(err);
    });
  }

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

  String getMinute(DateTime dateObj) {
    if (dateObj.minute == 0) {
      return dateObj.minute.toString() + "0";
    } else {
      return dateObj.minute.toString();
    }
  }

  void next(BuildContext context) {
    Navigator.push(
        context,
        FadePage(
            page: ObGyneTimeSlots(
                projectID: widget.doctor.projectID!,
                selectedClinicID: widget.doctor.clinicID!,
                selectedDoctorID: widget.doctor.doctorID!,
                obGyneProcedureListResponse: widget.obGyneProcedureListResponse!)));
  }

  Future navigateToDoctorProfile(context, docObject, docProfile, {isAppo, bool isContinueDentalPlan = false}) async {
    Navigator.push(
      context,
      FadePage(
        page: DoctorProfile(
          doctor: docObject,
          isLiveCareAppointment: widget.isLiveCareAppointment!,
          docProfileList: docProfile,
          isOpenAppt: isAppo,
          isDoctorNameSearch: widget.isDoctorNameSearch,
          isContinueDentalPlan: isContinueDentalPlan,
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
