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/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.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/get_clinic_list_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/doctor_rating_details.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/doctor_schedule_page.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.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:provider/provider.dart';

class DoctorProfilePage extends StatelessWidget {
  const DoctorProfilePage({super.key, required this.isDoctorAllowedToBook});

  final bool isDoctorAllowedToBook;

  @override
  Widget build(BuildContext context) {
    Clarity.setCurrentScreenName('Doctor Profile Page');
    final bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    final appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.profileOnlyText.tr(),
              trailing: appState.isAuthenticated
                  ? Consumer<BookAppointmentsViewModel>(
                      builder: (context, viewModel, child) {
                        return SizedBox(
                          width: 24.h,
                          height: 24.h,
                          child: Icon(
                            viewModel.isFavouriteDoctor ? Icons.bookmark : Icons.bookmark_border_outlined,
                            size: 36.h,
                            color: viewModel.isFavouriteDoctor ? AppColors.primaryRedColor : AppColors.textColor,
                          ).onPress(() async {
                            viewModel.toggleFavouriteDoctor();
                            await viewModel.insertFavouriteDoctor(
                              patientID: appState.getAuthenticatedUser()!.patientId!,
                              projectID: viewModel.doctorsProfileResponseModel.projectID ?? 0,
                              clinicID: viewModel.doctorsProfileResponseModel.clinicID ?? 0,
                              doctorID: viewModel.doctorsProfileResponseModel.doctorID ?? 0,
                              isActive: viewModel.isFavouriteDoctor,
                              onSuccess: (response) {
                                Utils.showToast(viewModel.isFavouriteDoctor
                                    ? LocaleKeys.doctorAddedToFavourite.tr(context: context)
                                    : LocaleKeys.doctorRemovedFromFavourite.tr(context: context));
                                // Successfully added/removed favorite - refresh the favorites list
                                getIt.get<MyAppointmentsViewModel>().refreshFavouriteDoctors();
                              },
                              onError: (error) {
                                // Revert the state on error
                                viewModel.toggleFavouriteDoctor();
                                Utils.showToast(error);
                              },
                            );
                          }),
                        );
                      },
                    )
                  : SizedBox.shrink(),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    isFoldable ? SizedBox(height: 24.h) : SizedBox.shrink(),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Utils.buildImgWithNetwork(
                              url: bookAppointmentsViewModel.doctorsProfileResponseModel.doctorImageURL!,
                              iconColor: AppColors.transparent,
                              width: 63.h,
                              height: 63.h,
                              fit: BoxFit.cover,
                            ).circle(100.r),
                            SizedBox(width: 8.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(
                                  width: isFoldable ? 250.w : 220.w,
                                  child:
                                      ("${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorTitleForProfile} ${bookAppointmentsViewModel.doctorsProfileResponseModel.doctorName}")
                                          .toString()
                                          .toText24(isBold: true),
                                ),
                                (bookAppointmentsViewModel.doctorsProfileResponseModel.specialty!.isNotEmpty
                                        ? bookAppointmentsViewModel.doctorsProfileResponseModel.specialty!.first
                                        : "")
                                    .toString()
                                    .toText18(isBold: true, color: AppColors.primaryRedColor),
                              ],
                            ),
                          ],
                        ),
                        Utils.buildImgWithNetwork(
                          url: bookAppointmentsViewModel.doctorsProfileResponseModel.nationalityFlagURL!,
                          iconColor: AppColors.transparent,
                          width: 32.h,
                          height: 32.h,
                          fit: BoxFit.cover,
                        ),
                      ],
                    ),
                    SizedBox(height: 12.h),
                    Wrap(
                      direction: Axis.horizontal,
                      spacing: 4.h,
                      runSpacing: 4.h,
                      children: [
                        AppCustomChipWidget(
                          backgroundColor: AppColors.whiteColor,
                          iconColor: AppColors.ratingColorYellow,
                          labelText: "${bookAppointmentsViewModel.doctorsProfileResponseModel.projectName}",
                        ),
                        AppCustomChipWidget(
                          backgroundColor: AppColors.whiteColor,
                          iconColor: AppColors.ratingColorYellow,
                          labelText: "${bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription}",
                        ),
                      ],
                    ),
                    SizedBox(height: 24.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Column(
                          children: [
                            Utils.buildSvgWithAssets(
                                icon: AppAssets.doctor_profile_rating_icon, width: 48.w, height: 48.h, fit: BoxFit.contain, applyThemeColor: false),
                            SizedBox(height: 16.h),
                            LocaleKeys.ratings.tr(context: context).toText12(isBold: true, color: AppColors.greyTextColor),
                            bookAppointmentsViewModel.doctorsProfileResponseModel.decimalDoctorRate.toString().toText16(
                                isBold: true,
                                color: AppColors.textColor,
                                isUnderLine: true,
                                decorationColor: AppColors.textColor,
                                fontFamily: "Poppins"),
                          ],
                        ).onPress(() {
                          bookAppointmentsViewModel.getDoctorRatingDetails();
                          showCommonBottomSheetWithoutHeight(
                            title: LocaleKeys.doctorRating.tr(context: context),
                            context,
                            child: DoctorRatingDetails(),
                            callBackFunc: () {},
                            isFullScreen: false,
                            isCloseButtonVisible: true,
                          );
                        }),
                        SizedBox(width: 36.w),
                        Column(
                          children: [
                            Utils.buildSvgWithAssets(
                                icon: AppAssets.doctor_profile_reviews_icon, width: 48.w, height: 48.h, fit: BoxFit.contain, applyThemeColor: false),
                            SizedBox(height: 16.h),
                            LocaleKeys.reviews.tr(context: context).toText12(isBold: true, color: AppColors.greyTextColor),
                            NumberFormat.decimalPattern("en_US")
                                .format(bookAppointmentsViewModel.doctorsProfileResponseModel.noOfPatientsRate ?? 0)
                                .toText16(
                                    isBold: true,
                                    color: AppColors.textColor,
                                    isUnderLine: true,
                                    decorationColor: AppColors.textColor,
                                    fontFamily: "Poppins"),
                          ],
                        ).onPress(() {
                          bookAppointmentsViewModel.getDoctorRatingDetails();
                          showCommonBottomSheetWithoutHeight(
                            title: LocaleKeys.doctorRating.tr(context: context),
                            context,
                            child: DoctorRatingDetails(),
                            callBackFunc: () {},
                            isFullScreen: false,
                            isCloseButtonVisible: true,
                          );
                        }),
                        SizedBox(width: 36.w),
                        Column(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.doctor_profile_schedule_icon, width: 48.w, height: 48.h, fit: BoxFit.contain, applyThemeColor: false),
                            SizedBox(height: 16.h),
                            LocaleKeys.schedule.tr(context: context).toText12(isBold: true, color: AppColors.greyTextColor),
                            LocaleKeys.view.tr(context: context).toText16(isBold: true, color: AppColors.textColor, isUnderLine: true, decorationColor: AppColors.textColor, fontFamily: "Poppins"),
                          ],
                        ).onPress(() {
                          _openDoctorSchedule(context);
                        })
                      ],
                    ),
                    SizedBox(height: 16.h),
                    Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                    SizedBox(height: 16.h),
                    LocaleKeys.information.tr(context: context).toText14(isBold: true, color: AppColors.textColor),
                    SizedBox(height: 6.h),
                    (bookAppointmentsViewModel.doctorsProfileResponseModel.doctorProfileInfo ?? "")
                        .trim()
                        .toText12(isBold: true, color: AppColors.greyTextColor),
                    SizedBox(height: 24.h),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
              ),
            ),
          ),
          isDoctorAllowedToBook
              ? Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 24.h,
                    hasShadow: true,
                  ),
                  child: CustomButton(
                    text: LocaleKeys.viewAvailableAppointments.tr(),
                    onPressed: () async {
                      bookAppointmentsViewModel.selectedDoctor.speciality = bookAppointmentsViewModel.doctorsProfileResponseModel.specialty;
                      bookAppointmentsViewModel.selectedDoctor.specialityN = bookAppointmentsViewModel.doctorsProfileResponseModel.specialty;
                      bookAppointmentsViewModel.selectedDoctor.name = bookAppointmentsViewModel.doctorsProfileResponseModel.doctorName;
                      bookAppointmentsViewModel.selectedDoctor.doctorImageURL = bookAppointmentsViewModel.doctorsProfileResponseModel.doctorImageURL;
                      bookAppointmentsViewModel.selectedDoctor.nationalityFlagURL =
                          bookAppointmentsViewModel.doctorsProfileResponseModel.nationalityFlagURL;
                      bookAppointmentsViewModel.selectedDoctor.clinicName = bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription;
                      bookAppointmentsViewModel.selectedDoctor.projectName = bookAppointmentsViewModel.doctorsProfileResponseModel.projectName;

                      final clinic = GetClinicsListResponseModel(
                        clinicID: bookAppointmentsViewModel.doctorsProfileResponseModel.clinicID,
                        clinicDescription: bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription,
                        clinicDescriptionN: bookAppointmentsViewModel.doctorsProfileResponseModel.clinicDescription,
                      );

                      bookAppointmentsViewModel.setSelectedClinic(clinic);

                      LoaderBottomSheet.showLoader();
                      bookAppointmentsViewModel.isLiveCareSchedule
                          ? await bookAppointmentsViewModel.getLiveCareDoctorFreeSlots(
                              isBookingForLiveCare: true,
                              onSuccess: (dynamic respData) async {
                                LoaderBottomSheet.hideLoader();
                                showCommonBottomSheetWithoutHeight(
                                  title: LocaleKeys.pickADate.tr(),
                                  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,
                                  child: AppointmentCalendar(),
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                  callBackFunc: () {},
                                );
                              },
                              onError: (err) {
                                LoaderBottomSheet.hideLoader();
                                showCommonBottomSheetWithoutHeight(
                                  context,
                                  child: Utils.getErrorWidget(loadingText: err),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              });
                    },
                    backgroundColor: AppColors.primaryRedColor,
                    borderColor: AppColors.primaryRedColor,
                    textColor: Colors.white,
                    fontSize: 16,
                    isBold: true,
                    borderRadius: 12,
                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                    height: 50.h,
                    icon: AppAssets.calendar,
                    iconColor: Colors.white,
                    iconSize: 20.h,
                  ).paddingSymmetrical(24.h, 24.h),
                )
              : SizedBox.shrink(),
        ],
      ),
    );
  }

  // Guard against double-tap opening two bottom sheets simultaneously
  static bool _scheduleInFlight = false;

  void _openDoctorSchedule(BuildContext context) async {
    if (_scheduleInFlight) return;
    _scheduleInFlight = true;

    final bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);

    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingDoctorSchedulePleaseWait.tr(context: context));

    // Yield to the frame scheduler so the loader is fully painted
    // before the API calls start (prevents the "loader appears late" glitch).
    await Future<void>.delayed(Duration.zero);

    if (bookAppointmentsViewModel.freeSlotsResponse == null || bookAppointmentsViewModel.freeSlotsResponse.isEmpty) {
      await bookAppointmentsViewModel.getDoctorFreeSlots(
        isBookingForLiveCare: false,
        onSuccess: (dynamic respData) async {
          await _fetchDoctorSchedule(context, bookAppointmentsViewModel);
        },
        onError: (err) {
          _scheduleInFlight = false;
          LoaderBottomSheet.hideLoader();
          showCommonBottomSheetWithoutHeight(
            context,
            child: Utils.getErrorWidget(loadingText: err),
            callBackFunc: () {},
            isFullScreen: true,
            isCloseButtonVisible: true,
          );
        },
      );
    } else {
      await _fetchDoctorSchedule(context, bookAppointmentsViewModel);
    }
  }

  Future<void> _fetchDoctorSchedule(BuildContext context, BookAppointmentsViewModel bookAppointmentsViewModel) async {
    await bookAppointmentsViewModel.getDoctorSchedule(
      doctorID: bookAppointmentsViewModel.selectedDoctor.doctorID!,
      projectID: bookAppointmentsViewModel.selectedDoctor.projectID!,
      clinicID: bookAppointmentsViewModel.selectedDoctor.clinicID!,
      doctorWorkingHoursDays: 90,
      onSuccess: (dynamic respData) async {
        _scheduleInFlight = false;
        LoaderBottomSheet.hideLoader();
        if (context.mounted) {
          await Navigator.of(context).push(
            CustomPageRoute(
              page: const DoctorSchedulePage(),
              fullScreenDialog: true,
              direction: AxisDirection.down,
            ),
          );
        }
      },
      onError: (err) {
        _scheduleInFlight = false;
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(
          context,
          child: Utils.getErrorWidget(loadingText: err),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      },
    );
  }
}
