import 'dart:convert';
import 'dart:developer';
import 'dart:typed_data';

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.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/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_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/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart';
import 'package:hmg_patient_app_new/features/symptoms_checker/symptoms_checker_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/waiting_appointment/waiting_appointment_payment_page.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.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:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class ReviewAppointmentPage extends StatefulWidget {
  const ReviewAppointmentPage({super.key});

  @override
  State<ReviewAppointmentPage> createState() => _ReviewAppointmentPageState();
}

class _ReviewAppointmentPageState extends State<ReviewAppointmentPage> {
  late AppState appState;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late AuthenticationViewModel authVM;
  late MyAppointmentsViewModel myAppointmentsViewModel;
  late SymptomsCheckerViewModel symptomsCheckerViewModel;

  Uint8List? _cachedImageBytes;
  String? _cachedImageDataHash;

  @override
  void initState() {
    Clarity.setCurrentScreenName('Appointment Review Page');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    authVM = Provider.of<AuthenticationViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    symptomsCheckerViewModel = Provider.of<SymptomsCheckerViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.reviewAppointment.tr(context: context),
              child: Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                return SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 24.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 24.h),
                      LocaleKeys.docInfo.tr(context: context).toText16(isBold: true),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.r,
                          hasShadow: false,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Utils.buildImgWithNetwork(
                                    url: bookAppointmentsViewModel.selectedDoctor.doctorImageURL ??
                                        "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown.png",
                                    iconColor: AppColors.transparent,
                                    width: 50.h,
                                    height: 50.h,
                                    fit: BoxFit.cover,
                                  ).circle(100),
                                  SizedBox(width: 8.h),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          "${bookAppointmentsViewModel.selectedDoctor.doctorTitle ?? LocaleKeys.Dr.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.name}"
                                              .toString()
                                              .toText16(isBold: true, maxlines: 1),
                                          SizedBox(width: 12.w),
                                          (bookAppointmentsViewModel.selectedDoctor.nationalityFlagURL != null &&
                                                  bookAppointmentsViewModel.selectedDoctor.nationalityFlagURL!.isNotEmpty)
                                              ? Utils.buildImgWithNetwork(
                                                  url: bookAppointmentsViewModel.selectedDoctor.nationalityFlagURL ??
                                                      "https://hmgwebservices.com/Images/flag/SAU.png",
                                                  iconColor: AppColors.transparent,
                                                  width: 20.h,
                                                  height: 15.h,
                                                  fit: BoxFit.cover,
                                                )
                                              : SizedBox.shrink(),
                                        ],
                                      ),
                                      SizedBox(height: 2.h),
                                      (bookAppointmentsViewModel.selectedDoctor.speciality!.isNotEmpty
                                              ? bookAppointmentsViewModel.selectedDoctor.speciality!.first
                                              : "")
                                          .toString()
                                          .toText12(isBold: true, color: AppColors.greyTextColor, maxLine: 1),
                                    ],
                                  ),
                                ],
                              ),
                              SizedBox(height: 12.h),
                              Wrap(
                                direction: Axis.horizontal,
                                spacing: 4.h,
                                runSpacing: 4.h,
                                children: [
                                  AppCustomChipWidget(
                                    labelText: "${LocaleKeys.clinic.tr(context: context)}: ${bookAppointmentsViewModel.selectedDoctor.clinicName}",
                                  ),
                                  AppCustomChipWidget(
                                    labelText: "${LocaleKeys.branch.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.projectName}",
                                  ),
                                  AppCustomChipWidget(
                                    labelText:
                                        "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? DateUtil.formatDateToDate(DateTime.now(), false) : bookAppointmentsViewModel.selectedAppointmentDisplayDate}",
                                  ),
                                  AppCustomChipWidget(
                                    labelText:
                                        "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.isWaitingAppointmentSelected ? LocaleKeys.waitingAppointment.tr(context: context) : bookAppointmentsViewModel.selectedAppointmentTime}",
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.h),
                      LocaleKeys.patientInfo.tr(context: context).toText16(isBold: true),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.r,
                          hasShadow: false,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Row(
                            children: [
                              // Image.asset(
                              //   appState.getAuthenticatedUser()?.gender == 1 ? AppAssets.maleImg : AppAssets.femaleImg,
                              //   width: 52.h,
                              //   height: 52.h,
                              // ),
                              Consumer<ProfileSettingsViewModel>(builder: (context, profileVm, _) {
                                return _buildProfileImage(profileVm);
                              }),
                              SizedBox(width: 8.h),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText16(isBold: true),
                                  SizedBox(height: 8.h),
                                  Wrap(
                                    direction: Axis.horizontal,
                                    spacing: 4.h,
                                    runSpacing: 4.h,
                                    children: [
                                      AppCustomChipWidget(
                                          labelText: "${appState.getAuthenticatedUser()!.age} ${LocaleKeys.yearsOld.tr(context: context)}"),
                                      AppCustomChipWidget(
                                          labelText:
                                              "${LocaleKeys.gender.tr(context: context)}: ${appState.getAuthenticatedUser()?.gender == 1 ? LocaleKeys.malE.tr(context: context) : LocaleKeys.femaleGender.tr(context: context)}"),
                                    ],
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.h),
                      LocaleKeys.hospitalInformation.tr(context: context).toText16(isBold: true),
                      SizedBox(height: 16.h),
                      Container(
                        width: double.infinity,
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.r,
                          hasShadow: false,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              (bookAppointmentsViewModel.selectedDoctor.projectName ?? "Habib Hospital").toText16(isBold: true),
                              SizedBox(height: 8.h),
                              bookAppointmentsViewModel.appointmentNearestGateResponseModel != null
                                  ? Wrap(
                                      direction: Axis.horizontal,
                                      spacing: 8.w,
                                      runSpacing: 8.h,
                                      children: [
                                        AppCustomChipWidget(
                                          labelText: bookAppointmentsVM.isAppointmentNearestGateLoading
                                              ? "Floor: Ground Floor"
                                              : "${LocaleKeys.floor.tr(context: context)} ${getIt.get<AppState>().isArabic() ? bookAppointmentsViewModel.appointmentNearestGateResponseModel!.clinicLocationN : bookAppointmentsViewModel.appointmentNearestGateResponseModel!.clinicLocation}",
                                        ).toShimmer2(isShow: bookAppointmentsVM.isAppointmentNearestGateLoading),
                                        AppCustomChipWidget(
                                                labelText:
                                                    "${LocaleKeys.nearestGate.tr(context: context)} ${getIt.get<AppState>().isArabic() ? bookAppointmentsVM.appointmentNearestGateResponseModel!.nearestGateNumberN : bookAppointmentsVM.appointmentNearestGateResponseModel!.nearestGateNumber}")
                                            .toShimmer2(isShow: bookAppointmentsVM.isAppointmentNearestGateLoading),
                                      ],
                                    )
                                  : SizedBox.shrink(),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.r,
              hasShadow: true,
            ),
            child: CustomButton(
              text: bookAppointmentsViewModel.isWaitingAppointmentSelected ? "Add to waiting list" : LocaleKeys.bookAppo.tr(context: context),
              onPressed: () async {
                if (bookAppointmentsViewModel.isWaitingAppointmentSelected) {
                  getWalkInAppointmentPatientShare();
                } else {
                  initiateBookAppointment();
                }
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: Colors.white,
              fontSize: 16.f,
              fontWeight: FontWeight.w600,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 50.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }

  Widget _buildProfileImage(ProfileSettingsViewModel profileVm) {
    // Always get fresh user data
    final currentUser = appState.getAuthenticatedUser();
    final currentPatientId = currentUser?.patientId;
    final gender = currentUser?.gender ?? 1;
    final age = currentUser?.age ?? 0;

    // Determine the default image based on gender and age
    final String defaultImage;
    if (gender == 1) {
      // Male
      defaultImage = age < 7 ? AppAssets.babyBoyImg : AppAssets.maleImg;
    } else {
      // Female
      defaultImage = age < 7 ? AppAssets.babyGirlImg : AppAssets.femaleImg;
    }

    // Show selected image if available (only during upload)
    // if (_selectedImage != null) {
    //   return ClipOval(
    //     child: Image.file(
    //       _selectedImage!,
    //       width: 136.w,
    //       height: 136.h,
    //       fit: BoxFit.cover,
    //     ),
    //   );
    // }

    // Use cached decoded bytes — update cache if source data changed
    final String? imageData = GetIt.instance<AppState>().getProfileImageData;
    final String? currentHash = (imageData != null && imageData.isNotEmpty) ? '${imageData.length}_${imageData.hashCode}' : null;

    // Re-decode only if the underlying data actually changed
    if (currentHash != null && currentHash != _cachedImageDataHash) {
      try {
        _cachedImageBytes = base64Decode(imageData!);
        _cachedImageDataHash = currentHash;
      } catch (e) {
        print('❌ Error decoding profile image: $e');
        _cachedImageBytes = null;
        _cachedImageDataHash = null;
      }
    } else if (currentHash == null) {
      _cachedImageBytes = null;
      _cachedImageDataHash = null;
    }

    // Show cached decoded image if available
    if (_cachedImageBytes != null) {
      return ClipOval(
        child: Image.memory(
          _cachedImageBytes!,
          key: ValueKey('profile_$currentPatientId'),
          width: 52.w,
          height: 52.h,
          fit: BoxFit.cover,
          gaplessPlayback: true, // Prevents blink during image rebuild
        ),
      );
    }

    // Show default image (no image data or user has no uploaded image)
    print('📷 Showing default avatar for user $currentPatientId');
    return Utils.buildImgWithAssets(
      icon: defaultImage,
      width: 52.w,
      height: 52.h,
    );
  }

  void getWalkInAppointmentPatientShare() async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingAppointmentShare.tr(context: context));
    await bookAppointmentsViewModel.getWalkInPatientShareAppointment(onSuccess: (val) {
      LoaderBottomSheet.hideLoader();
      if (bookAppointmentsViewModel.patientWalkInAppointmentShareResponseModel!.patientShareWithTax != 0 ||
          bookAppointmentsViewModel.patientWalkInAppointmentShareResponseModel!.patientShareWithTax != 0.0) {
        Navigator.of(context).push(
          CustomPageRoute(
            page: WaitingAppointmentPaymentPage(),
          ),
        );
      } else {
        initiateBookAppointmentForWalkInNoPatientShare();
      }
    }, onError: (err) {
      LoaderBottomSheet.hideLoader();
      showCommonBottomSheetWithoutHeight(
        context,
        child: Utils.getErrorWidget(loadingText: err),
        callBackFunc: () {},
        isFullScreen: false,
        isCloseButtonVisible: true,
      );
    });
  }

  void initiateBookAppointmentForWalkInNoPatientShare() async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.bookingWaitingAppointment.tr(context: context));
    await bookAppointmentsViewModel.insertSpecificAppointmentForWalkIn(onSuccess: (val) async {
      String appointmentNo = val.data['AppointmentNo'].toString();
      LoaderBottomSheet.hideLoader();
      sendCheckInRequest(bookAppointmentsViewModel.waitingAppointmentNFCCode, appointmentNo, context);
    });
  }

  void sendCheckInRequest(String scannedCode, String appointmentNo, BuildContext context) async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingCheckIn.tr(context: context));
    PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel = PatientAppointmentHistoryResponseModel(
      appointmentNo: appointmentNo,
      clinicID: bookAppointmentsViewModel.selectedDoctor.clinicID,
      projectID: bookAppointmentsViewModel.selectedDoctor.projectID,
    );
    await myAppointmentsViewModel.sendCheckInNfcRequest(
      patientAppointmentHistoryResponseModel: patientAppointmentHistoryResponseModel,
      scannedCode: scannedCode,
      checkInType: 2,
      onSuccess: (apiResponse) {
        LoaderBottomSheet.hideLoader();
        myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);
        myAppointmentsViewModel.getPatientAppointments(true, false);
        showCommonBottomSheetWithoutHeight(context,
            title: LocaleKeys.success.tr(context: context),
            child: Utils.getSuccessWidget(loadingText: apiResponse.data["SuccessMsg"]), callBackFunc: () {
          Navigator.of(context).pop();
          Navigator.pushAndRemoveUntil(
              context,
              CustomPageRoute(
                page: LandingNavigation(),
              ),
              (r) => false);
        }, isFullScreen: false);
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.error.tr(context: context), child: Utils.getErrorWidget(loadingText: error),
            callBackFunc: () {
          Navigator.of(context).pop();
        }, isFullScreen: false);
      },
    );
  }

  void initiateBookAppointment() async {
    // LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: bookAppointmentsViewModel.isPatientRescheduleAppointment ? LocaleKeys.reschedulingAppo.tr(context: context) : LocaleKeys.bookingYourAppointment.tr(context: context));
    Clarity.sendCustomEvent('Appointment_book_success');
    LoaderBottomSheet.showLoader(
        loadingText: bookAppointmentsViewModel.isPatientRescheduleAppointment
            ? LocaleKeys.reschedulingAppo.tr(context: context)
            : LocaleKeys.bookingYourAppointment.tr(context: context));
    myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);

    if (bookAppointmentsViewModel.isLiveCareSchedule) {
      await bookAppointmentsViewModel.insertSpecificAppointmentForLiveCare(onError: (err) {
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(
          title: LocaleKeys.notice.tr(context: context),
          context,
          child: Utils.getErrorWidget(loadingText: err.toString()),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      }, onSuccess: (apiResp) async {
        LoaderBottomSheet.hideLoader();
        await Future.delayed(Duration(milliseconds: 50)).then((value) async {
          // LoaderBottomSheet.showLoader(loadingText: LocaleKeys.appointmentSuccess.tr());
          showCommonBottomSheetWithoutHeight(context, child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentSuccess.tr()),
              callBackFunc: () {
            bookAppointmentsViewModel.setIsPatientRescheduleAppointment(false);
            bookAppointmentsViewModel.setIsLiveCareSchedule(false);
            bookAppointmentsViewModel.setSelectedChiefComplaintID(0);
            Navigator.pushAndRemoveUntil(
                context,
                CustomPageRoute(
                  page: LandingNavigation(),
                ),
                (r) => false);
          }, isFullScreen: false, isCloseButtonVisible: false, isAutoDismiss: true);
        });
      });
    } else {
      //TODO: Add patient Derma package check API Here
      await bookAppointmentsViewModel.insertSpecificAppointment(onError: (err) {
        // print(err.data["ErrorEndUserMessage"]);
        LoaderBottomSheet.hideLoader();
        showCommonBottomSheetWithoutHeight(
          title: LocaleKeys.notice.tr(context: context),
          context,
          child: Utils.getErrorWidget(loadingText: err.toString()),
          callBackFunc: () {
            myAppointmentsViewModel.initAppointmentsViewModel();
            myAppointmentsViewModel.getPatientAppointments(true, false);
            // Navigator.pop(context);
          },
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      }, onSuccess: (apiResp) async {
        log("AppointmentNo: ${symptomsCheckerViewModel.isBookingFromSymptomsChecker}");
        // Check if booking is from symptoms checker and call the API
        if (symptomsCheckerViewModel.isBookingFromSymptomsChecker) {
          final appointmentNo = apiResp.data['AppointmentNo']?.toString() ?? '';
          final doctorId = bookAppointmentsViewModel.selectedDoctor.doctorID?.toString() ?? '';

          // Convert date and time to ISO 8601 format with timezone
          DateTime? appointmentDateTime;
          try {
            // Combine date (YYYY-MM-DD) and time (HH:MM) into ISO format string
            final dateTimeString = '${bookAppointmentsViewModel.selectedAppointmentDate}T${bookAppointmentsViewModel.selectedAppointmentTime}:00';
            appointmentDateTime = DateTime.parse(dateTimeString);
          } catch (e) {
            log("Error parsing appointment date/time: $e");
          }

          // Convert to ISO 8601 format with UTC timezone (e.g., "2026-02-11T13:15:37.652Z")
          final appointmentDate = appointmentDateTime != null ? DateUtil.getISODateFormat(appointmentDateTime.toUtc()) : '';
          final mobileNumber = appState.getAuthenticatedUser()?.mobileNumber ?? '';
          final fileNo = appState.getAuthenticatedUser()?.patientId?.toString() ?? '';
          final projectId = bookAppointmentsViewModel.selectedDoctor.projectID ?? 0;
          final clinicId = bookAppointmentsViewModel.selectedDoctor.clinicID ?? 0;

          await symptomsCheckerViewModel.saveAppointmentDetailsForSymptomsChecker(
            fileNo: fileNo,
            appointmentNo: appointmentNo,
            doctorId: doctorId,
            appointmentDate: appointmentDate,
            mobileNumber: mobileNumber,
            projectId: projectId,
            clinicId: clinicId,
            onSuccess: (response) {
              // Success - continue with normal flow
              debugPrint("onSuccess called for saveAppointmentDetailsForSymptomsChecker: ${response.data}");
            },
            onError: (error) {
              // Log error but don't block the user flow
              debugPrint("Error saving symptoms checker appointment: $error");
            },
          );
        }

        LoaderBottomSheet.hideLoader();
        await Future.delayed(Duration(milliseconds: 50)).then((value) async {
          showCommonBottomSheetWithoutHeight(context,
              child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentSuccess.tr()).paddingSymmetrical(0.h, 24.h), callBackFunc: () {
            bookAppointmentsViewModel.setIsLiveCareSchedule(false);
            bookAppointmentsViewModel.setIsPatientRescheduleAppointment(false);
            bookAppointmentsViewModel.setSelectedChiefComplaintID(0);
            Navigator.pushAndRemoveUntil(context, CustomPageRoute(page: LandingNavigation()), (r) => false);
          }, isFullScreen: false, isCloseButtonVisible: false, isAutoDismiss: true);
        });
      });
    }
  }
}
