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/app_state.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/book_appointments/models/resp_models/get_clinic_list_response_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/dental_chief_complaints_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/laser/laser_appointment.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.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';
import 'package:lottie/lottie.dart';
import 'package:url_launcher/url_launcher.dart';

class DoctorCard extends StatelessWidget {
  const DoctorCard({
    super.key,
    required this.doctorsListResponseModel,
    required this.isLoading,
    this.isDoctorNameSearch = false,
    required this.bookAppointmentsViewModel,
  });

  final DoctorsListResponseModel doctorsListResponseModel;
  final bool isLoading;
  final bool isDoctorNameSearch;

  final BookAppointmentsViewModel bookAppointmentsViewModel;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: false,
      ),
      child: Padding(
        padding: EdgeInsets.only(top: 14.h, bottom: 20.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Utils.buildImgWithNetwork(
                      url: isLoading
                          ? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png"
                          : doctorsListResponseModel.doctorImageURL ?? "https://hmgwebservices.com/Images/MobileImages/OALAY/1439.png",
                      iconColor: AppColors.transparent,
                      width: 63.h,
                      height: 63.h,
                      fit: BoxFit.cover,
                    ).circle(100).toShimmer2(isShow: isLoading),
                    Transform.translate(
                      offset: Offset(0.0, -20.h),
                      child: Container(
                        width: 40.w,
                        height: 40.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.w, height: 15.h, applyThemeColor: false),
                            SizedBox(height: 2.h),
                            "${isLoading ? 4.78 : doctorsListResponseModel.decimalDoctorRate}".toText11(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                          ],
                        ),
                      ).circle(100).toShimmer2(isShow: isLoading),
                    ),
                  ],
                ),
                SizedBox(width: 8.h),
                Expanded(
                  flex: 9,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          SizedBox(
                            width: MediaQuery.of(context).size.width * 0.55,
                            child: (isLoading ? "Dr John Smith" : "${doctorsListResponseModel.doctorTitle} ${doctorsListResponseModel.name}").toString().toText16(isBold: true, maxlines: 1),
                          ).toShimmer2(isShow: isLoading),
                        ],
                      ),
                      SizedBox(height: 2.h),
                      Row(
                        children: [
                          SizedBox(
                            child: (isLoading
                                    ? "Consultant Cardiologist"
                                    : (getIt.get<AppState>().isArabic() && doctorsListResponseModel.specialityN != null)
                                        ? doctorsListResponseModel.specialityN!.isNotEmpty
                                            ? (doctorsListResponseModel.specialityN!.first.length > 32
                                                ? '${doctorsListResponseModel.specialityN!.first.substring(0, 32)}...'
                                                : doctorsListResponseModel.specialityN!.first)
                                            : ""
                                        : doctorsListResponseModel.speciality != null ?
                            doctorsListResponseModel.speciality!.isNotEmpty
                                            ? (doctorsListResponseModel.speciality!.first.length > 32
                                                ? '${doctorsListResponseModel.speciality!.first.substring(0, 32)}...'
                                                : doctorsListResponseModel.speciality!.first) : ""
                                        : "")
                                .toString()
                                .toText12(isBold: true, color: AppColors.textColor, maxLine: 2, isEnglishOnly: true)
                                .toShimmer2(isShow: isLoading),
                        ),
                        SizedBox(width: 6.w),
                        Utils.buildImgWithNetwork(
                          url: isLoading ? "https://hmgwebservices.com/Images/flag/SYR.png" : doctorsListResponseModel.nationalityFlagURL ?? "https://hmgwebservices.com/Images/flag/SYR.png",
                          iconColor: AppColors.transparent,
                          width: 20.h,
                          height: 15.h,
                          fit: BoxFit.fill,
                        ).toShimmer2(isShow: isLoading),
                      ],
                      ),
                      SizedBox(height: 6.h),
                      Wrap(
                        direction: Axis.horizontal,
                        spacing: 3.h,
                        runSpacing: 4.h,
                        children: [
                          // bookAppointmentsViewModel.isNearestAppointmentSelected
                          //     ?
                          doctorsListResponseModel.nearestFreeSlot != null
                                  ? AppCustomChipWidget(
                                      labelText: (isLoading ? "Cardiologist" : DateUtil.getDateStringForNearestSlot(doctorsListResponseModel.nearestFreeSlot)),
                                      // richText: (isLoading ? "Cardiologist" : DateUtil.getDateStringForNearestSlot(doctorsListResponseModel.nearestFreeSlot))
                                      //     .toText10(isEnglishOnly: true, color: AppColors.textColor),
                                      backgroundColor: AppColors.successColor.withValues(alpha: .15),
                                      isEnglishOnly: true,
                                      textColor: AppColors.successColor,
                                    ).toShimmer2(isShow: isLoading)
                                  : SizedBox.shrink()
                              // : SizedBox.shrink()
                          ,
                          AppCustomChipWidget(
                            labelText: "${isLoading ? "Cardiologist" : doctorsListResponseModel.clinicName}",
                          ).toShimmer2(isShow: isLoading),
                          AppCustomChipWidget(
                            labelText: "${isLoading ? "Olaya Hospital" : doctorsListResponseModel.projectName}",
                          ).toShimmer2(isShow: isLoading),
                        ],
                      ),
                    ],
                  ),
                ),
                // (doctorsListResponseModel.isLiveCare ?? true)
                //     ? SizedBox.shrink()
                //     :
                Expanded(
                        flex: 1,
                        child: Utils.buildSvgWithAssets(icon: AppAssets.doctor_profile_icon, width: 20.h, height: 20.h, fit: BoxFit.scaleDown).toShimmer2(isShow: isLoading),
                      ),
              ],
            ),
            SizedBox(height: 16.h),
            CustomButton(
              text: LocaleKeys.bookAppo.tr(context: context),
              onPressed: () async {
                if (isDoctorNameSearch && doctorsListResponseModel.clinicID == 17) {
                  GetClinicsListResponseModel selectedClinic = GetClinicsListResponseModel(
                      clinicID: doctorsListResponseModel.clinicID, clinicDescription: doctorsListResponseModel.clinicName, isLiveCareClinicAndOnline: false, liveCareServiceID: 0, liveCareClinicID: 0);
                  bookAppointmentsViewModel.setProjectID(doctorsListResponseModel.projectID.toString());
                  bookAppointmentsViewModel.setSelectedClinic(selectedClinic);
                  bookAppointmentsViewModel.setIsChiefComplaintsListLoading(true);
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: DentalChiefComplaintsPage(),
                    ),
                  );
                } else if (isDoctorNameSearch && doctorsListResponseModel.clinicID == 253) {
                  GetClinicsListResponseModel selectedClinic = GetClinicsListResponseModel(
                      clinicID: doctorsListResponseModel.clinicID, clinicDescription: doctorsListResponseModel.clinicName, isLiveCareClinicAndOnline: false, liveCareServiceID: 0, liveCareClinicID: 0);
                  bookAppointmentsViewModel.setSelectedClinic(selectedClinic);
                  bookAppointmentsViewModel.getLaserClinic();
                  bookAppointmentsViewModel.setIsDoctorsListLoading(true);
                  Navigator.of(context).push(
                    CustomPageRoute(
                      page: LaserAppointment(),
                    ),
                  );
                } else {
                  bookAppointmentsViewModel.setSelectedDoctor(doctorsListResponseModel);
                  LoaderBottomSheet.showLoader();
                  bookAppointmentsViewModel.isLiveCareSchedule
                      ? await bookAppointmentsViewModel.getLiveCareDoctorFreeSlots(
                          isBookingForLiveCare: true,
                          onSuccess: (dynamic respData) async {
                            LoaderBottomSheet.hideLoader();
                            showCommonBottomSheetWithoutHeight(
                              title: LocaleKeys.pickADate.tr(context: context),
                              context,
                              child: AppointmentCalendar(),
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                              callBackFunc: () {},
                            );
                          },
                          onError: (err) {
                            LoaderBottomSheet.hideLoader();
                            showCommonBottomSheetWithoutHeight(
                              context,
                              child: Utils.getErrorWidget(loadingText: err),
                              callBackFunc: () {},
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                            );
                          })
                      : await bookAppointmentsViewModel.getDoctorFreeSlots(
                          isBookingForLiveCare: false,
                          onSuccess: (dynamic respData) async {
                            LoaderBottomSheet.hideLoader();
                            showCommonBottomSheetWithoutHeight(
                              title: LocaleKeys.pickADate.tr(context: context),
                              context,
                              child: AppointmentCalendar(),
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                              callBackFunc: () {},
                            );
                          },
                          onError: (err) {
                            LoaderBottomSheet.hideLoader();
                            if (bookAppointmentsViewModel.selectedClinic.clinicID == 23) {
                              showCommonBottomSheetWithoutHeight(
                                context,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                                    SizedBox(height: 8.h),
                                    ("For booking appointments in the Physiotherapy clinic, please contact: 920066666").toText16(color: AppColors.blackColor),
                                    SizedBox(height: 16.h),
                                    CustomButton(
                                        height: 40.h,
                                        backgroundColor: AppColors.primaryRedColor,
                                        borderColor: AppColors.primaryRedColor,
                                        text: LocaleKeys.callNow.tr(),
                                        textColor: AppColors.whiteColor,
                                        iconColor: AppColors.whiteColor,
                                        onPressed: () {
                                          launchUrl(
                                            Uri.parse("tel://920066666"),
                                          );
                                        },
                                        icon: AppAssets.call),
                                  ],
                                ).center,
                                callBackFunc: () {},
                                isFullScreen: false,
                                isCloseButtonVisible: true,
                              );
                            } else {
                              showCommonBottomSheetWithoutHeight(
                                context,
                                child: Utils.getErrorWidget(loadingText: err),
                                callBackFunc: () {},
                                isFullScreen: false,
                                isCloseButtonVisible: true,
                              );
                            }
                            // showCommonBottomSheetWithoutHeight(
                            //   context,
                            //   child: Utils.getErrorWidget(loadingText: err),
                            //   callBackFunc: () {},
                            //   isFullScreen: false,
                            //   isCloseButtonVisible: true,
                            // );
                          });
                }
              },
              backgroundColor: Color(0xffFEE9EA),
              borderColor: Color(0xffFEE9EA),
              textColor: Color(0xffED1C2B),
              fontSize: 14.f,
              isBold: true,
              borderRadius: 10.r,
              padding: EdgeInsets.fromLTRB(10.h, 0, 10.h, 0),
              height: 40.h,
              icon: AppAssets.add_icon,
              iconColor: AppColors.primaryRedColor,
              iconSize: 15.h,
            ).toShimmer2(isShow: isLoading),
          ],
        ),
      ),
    );
  }
}
