import 'dart:ui' as ui;

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/utils/appointment_type.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';

class AppointmentDoctorCard extends StatelessWidget {
  const AppointmentDoctorCard(
      {super.key,
      required this.patientAppointmentHistoryResponseModel,
      required this.onRescheduleTap,
      required this.onCancelTap,
      required this.onAskDoctorTap,
      this.renderWidgetForERDisplay = false,
      this.timerWidget});

  final PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel;
  final VoidCallback onRescheduleTap;
  final VoidCallback onCancelTap;
  final VoidCallback onAskDoctorTap;
  final bool renderWidgetForERDisplay;

  final Widget? timerWidget;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 20.h,
        hasShadow: true,
      ),
      child: Padding(
        padding: EdgeInsets.all(14.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  children: [
                    Utils.buildImgWithNetwork(
                      url: patientAppointmentHistoryResponseModel.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png",
                      iconColor: AppColors.transparent,
                      width: 63.h,
                      height: 63.h,
                      fit: BoxFit.cover,
                    ).circle(100.r),
                    Transform.translate(
                      offset: Offset(0.0, -20.h),
                      child: Container(
                        width: 50.h,
                        height: 50.h,
                        decoration: BoxDecoration(
                          color: AppColors.whiteColor,
                          shape: BoxShape.circle, // Makes the container circular
                          border: Border.all(
                            color: AppColors.scaffoldBgColor, // Color of the border
                            width: 1.5.w, // Width of the border
                          ),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.rating_icon, width: 15.h, height: 15.h, iconColor: AppColors.ratingColorYellow),
                            SizedBox(height: 2.h),
                            "${patientAppointmentHistoryResponseModel.decimalDoctorRate ?? 0.0}"
                                .toText11(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                          ],
                        ),
                      ).circle(100),
                    ),
                  ],
                ),
                SizedBox(width: 16.w),
                Expanded(
                  flex: 9,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: (patientAppointmentHistoryResponseModel.doctorNameObj ?? "").toText16(
                              isBold: true,
                              isEnglishOnly: !Utils.isArabicText(patientAppointmentHistoryResponseModel.doctorNameObj ?? ""),
                              textOverflow: TextOverflow.ellipsis,
                              maxlines: 2
                            ),
                          ),
                          SizedBox(width: 12.w),
                          // (patientAppointmentHistoryResponseModel.doctorNationalityFlagURL != null &&
                          //         patientAppointmentHistoryResponseModel.doctorNationalityFlagURL!.isNotEmpty)
                          //     ? Image.network(
                          //         patientAppointmentHistoryResponseModel.doctorNationalityFlagURL ?? "https://hmgwebservices.com/Images/flag/SAU.png",
                          //         width: 20.h,
                          //         height: 15.h,
                          //         fit: BoxFit.cover,
                          //       )
                          //     : SizedBox.shrink(),
                        ],
                      ),
                      SizedBox(height: 8.h),
                      Wrap(
                        direction: Axis.horizontal,
                        spacing: 6.w,
                        runSpacing: 6.h,
                        children: [
                          AppCustomChipWidget(
                            labelText: ((patientAppointmentHistoryResponseModel.clinicName ?? "").length > 20
                                ? '${(patientAppointmentHistoryResponseModel.clinicName ?? "").substring(0, 20)}...'
                                : (patientAppointmentHistoryResponseModel.clinicName ?? "")),
                            labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 4.w),
                          ),
                          AppCustomChipWidget(
                            labelText: patientAppointmentHistoryResponseModel.projectName ?? "Habib Hospital",
                            labelPadding: EdgeInsetsDirectional.only(start: 6.w, end: 6.w),
                          ),
                          ClarityUnmask(
                            child: Directionality(
                              textDirection: ui.TextDirection.ltr,
                              child: AppCustomChipWidget(
                                labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 6.w),
                                icon: AppAssets.doctor_calendar_icon,
                                richText: "${DateUtil.formatDateToDate(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate), false)} ${DateUtil.formatDateToTimeLang(
                                  DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate),
                                  false,
                                )}"
                                    .toText10(isBold: true),
                              ),
                            ),
                          ),
                          AppCustomChipWidget(
                            labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 6.w),
                            icon: !patientAppointmentHistoryResponseModel.isLiveCareAppointment!
                                ? AppAssets.walkin_appointment_icon
                                : AppAssets.small_livecare_icon,
                            iconColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.textColor : Colors.white,
                            labelText: patientAppointmentHistoryResponseModel.isLiveCareAppointment!
                                ? LocaleKeys.livecare.tr(context: context)
                                : LocaleKeys.walkin.tr(context: context),
                            backgroundColor:
                                !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.greyColor : AppColors.successColor,
                            textColor: !patientAppointmentHistoryResponseModel.isLiveCareAppointment! ? AppColors.textColor : Colors.white,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                (patientAppointmentHistoryResponseModel.isLiveCareAppointment! ||
                    patientAppointmentHistoryResponseModel.isExecludeDoctor! ||
                        patientAppointmentHistoryResponseModel.isClinicReBookingAllowed! == false ||
                        patientAppointmentHistoryResponseModel.isActiveDoctor! == false ||
                    !Utils.isClinicAllowedForRebook(patientAppointmentHistoryResponseModel.clinicID))
                    ? SizedBox.shrink()
                    : Utils.buildSvgWithAssets(icon: AppAssets.doctor_profile_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown)
                        .onPress(() async {
                        DoctorsListResponseModel selectedDoctor = DoctorsListResponseModel();
                        selectedDoctor.doctorID = patientAppointmentHistoryResponseModel.doctorID;
                        selectedDoctor.doctorImageURL = patientAppointmentHistoryResponseModel.doctorImageURL;
                        selectedDoctor.name = patientAppointmentHistoryResponseModel.doctorNameObj;
                        selectedDoctor.doctorTitle = patientAppointmentHistoryResponseModel.doctorTitle;
                        selectedDoctor.nationalityFlagURL = "";
                        selectedDoctor.speciality = patientAppointmentHistoryResponseModel.doctorSpeciality;
                        selectedDoctor.clinicName = patientAppointmentHistoryResponseModel.clinicName;
                        selectedDoctor.projectName = patientAppointmentHistoryResponseModel.projectName;
                        selectedDoctor.clinicID = patientAppointmentHistoryResponseModel.clinicID;
                        selectedDoctor.projectID = patientAppointmentHistoryResponseModel.projectID;

                        getIt.get<BookAppointmentsViewModel>().setSelectedDoctor(selectedDoctor);
                        LoaderBottomSheet.showLoader();
                        await getIt.get<BookAppointmentsViewModel>().getDoctorProfile(onSuccess: (dynamic respData) {
                          LoaderBottomSheet.hideLoader();
                          Navigator.of(context).push(
                            CustomPageRoute(
                              page: DoctorProfilePage(
                                isDoctorAllowedToBook: !(patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false),
                              ),
                            ),
                          );
                        }, onError: (err) {
                          LoaderBottomSheet.hideLoader();
                          showCommonBottomSheetWithoutHeight(
                            context,
                            child: Utils.getErrorWidget(loadingText: err),
                            callBackFunc: () {},
                            isFullScreen: false,
                            isCloseButtonVisible: true,
                          );
                        });
                      })
              ],
            ),
            SizedBox(height: 8.h),
            Visibility(
              visible: renderWidgetForERDisplay == false,
              child: getAppointmentActionButtons(
                AppointmentType.isArrived(patientAppointmentHistoryResponseModel),
              ),
            ),
            if (!AppointmentType.isArrived(patientAppointmentHistoryResponseModel) && timerWidget != null) timerWidget ?? SizedBox()
          ],
        ),
      ),
    );
  }

  Widget getAppointmentActionButtons(bool isAppointmentArrived) {
    if (isAppointmentArrived) {
      return DateTime.now().difference(DateUtil.convertStringToDate(patientAppointmentHistoryResponseModel.appointmentDate)).inDays <= 15
          ? CustomButton(
              text: LocaleKeys.askDoctor.tr(),
              onPressed: () {
                onAskDoctorTap();
              },
              backgroundColor: AppColors.secondaryLightRedColor,
              borderColor: AppColors.secondaryLightRedColor,
              textColor: AppColors.primaryRedColor,
              fontSize: 14.f,
              isBold: true,
              borderRadius: 12.r,
              padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
              height: 40.h,
              iconSize: 16.h,
              icon: AppAssets.ask_doctor_icon,
              iconColor: AppColors.primaryRedColor,
            )
          :
          // !patientAppointmentHistoryResponseModel.isLiveCareAppointment!
          //         ? CustomButton(
          //             text: LocaleKeys.rebookSameDoctor.tr(),
          //             onPressed: () {
          //               onRescheduleTap();
          //             },
          //             backgroundColor: AppColors.greyColor,
          //             borderColor: AppColors.greyColor,
          //             textColor: AppColors.blackColor,
          //             fontSize: 12.f,
          //             isBold: true,
          //             borderRadius: 12.r,
          //             padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
          //             height: 40.h,
          //             icon: AppAssets.rebook_appointment_icon,
          //             iconColor: AppColors.blackColor,
          //             iconSize: 14.h,
          //           )
          //         :
          SizedBox.shrink();
    } else {
      return patientAppointmentHistoryResponseModel.isLiveCareAppointment!
          ? CustomButton(
              text: LocaleKeys.cancel.tr(),
              onPressed: () {
                onCancelTap();
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 14.f,
              isBold: true,
              borderRadius: 12.r,
              height: 40.h,
              icon: AppAssets.cancel,
              iconColor: AppColors.whiteColor,
              iconSize: 16.h,
            )
          : Row(
              children: [
                Expanded(
                  child: CustomButton(
                    text: LocaleKeys.reschedule.tr(),
                    onPressed: () {
                      onRescheduleTap();
                    },
                    backgroundColor: AppColors.secondaryLightRedColor,
                    borderColor: AppColors.secondaryLightRedColor,
                    textColor: AppColors.primaryRedColor,
                    fontSize: 14.f,
                    isBold: true,
                    borderRadius: 12.r,
                    height: 46.h,
                    icon: AppAssets.appointment_calendar_icon,
                    iconColor: AppColors.primaryRedColor,
                    iconSize: 16.h,
                  ),
                ),
                SizedBox(width: 16.h),
                Expanded(
                  child: CustomButton(
                    text: LocaleKeys.cancel.tr(),
                    onPressed: () {
                      onCancelTap();
                    },
                    backgroundColor: AppColors.primaryRedColor,
                    borderColor: AppColors.primaryRedColor,
                    textColor: AppColors.whiteColor,
                    fontSize: 14.f,
                    isBold: true,
                    borderRadius: 12.r,
                    height: 46.h,
                    icon: AppAssets.cancel,
                    iconColor: AppColors.whiteColor,
                    iconSize: 16.h,
                  ),
                ),
              ],
            );
    }
  }
}
