import 'dart:async';
import 'dart:ui' as ui;

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/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/my_appointments/utils/appointment_type.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/appointment_details_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/appointment_payment_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/routes/custom_page_route.dart';

class MedicalFileAppointmentCard extends StatefulWidget {
  final PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel;
  final MyAppointmentsViewModel myAppointmentsViewModel;
  final Function onRescheduleTap;
  final Function onAskDoctorTap;

  const MedicalFileAppointmentCard({
    super.key,
    required this.patientAppointmentHistoryResponseModel,
    required this.myAppointmentsViewModel,
    required this.onRescheduleTap,
    required this.onAskDoctorTap,
  });

  @override
  State<MedicalFileAppointmentCard> createState() => _MedicalFileAppointmentCardState();
}

class _MedicalFileAppointmentCardState extends State<MedicalFileAppointmentCard> {
  Timer? _countdownTimer;
  Duration? _timeRemaining;
  Function(void Function())? _modalSetState;

  @override
  void initState() {
    super.initState();
    // Start countdown timer if appointment requires payment
    if (widget.patientAppointmentHistoryResponseModel.nextAction == 15) {
      _startCountdownTimer();
    }
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }

  void _startCountdownTimer() {
    final appointmentDate = DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate!);
    final expiryDate = appointmentDate.subtract(const Duration(hours: 4));

    setState(() {
      _timeRemaining = expiryDate.difference(DateTime.now());
    });

    _countdownTimer?.cancel();
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final newTimeRemaining = expiryDate.difference(DateTime.now());

      if (newTimeRemaining.isNegative) {
        timer.cancel();
        setState(() {
          _timeRemaining = Duration.zero;
        });
        _modalSetState?.call(() {
          _timeRemaining = Duration.zero;
        });
      } else {
        setState(() {
          _timeRemaining = newTimeRemaining;
        });
        _modalSetState?.call(() {
          _timeRemaining = newTimeRemaining;
        });
      }
    });
  }

  // Helper method to build each time unit (number + label)
  Widget _buildTimeUnit(String value, String label) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          child: value.toText32(
            isBold: true,
            color: AppColors.blackColor,
            isEnglishOnly: true,
          ),
        ),
        SizedBox(height: 4.h),
        Container(
          alignment: Alignment.center,
          child: label.toText12(
            color: AppColors.greyTextColor,
          ),
        ),
      ],
    );
  }

  // Helper method to build time separator (:)
  Widget _buildTimeSeparator() {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h, left: 6.w, right: 6.w),
      child: ':'.toText32(
        isBold: true,
        color: AppColors.blackColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        AppCustomChipWidget(
          richText: Directionality(
            textDirection: ui.TextDirection.ltr,
            child: DateUtil.formatDateToDate(DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate), false)
                .toText12(
                    color: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) ? AppColors.textColor : AppColors.primaryRedColor,
                    isBold: true,
                    isEnglishOnly: true)
                .paddingSymmetrical(8.w, 0),
          ),
          icon: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)
              ? AppAssets.appointment_calendar_icon
              : AppAssets.alarm_clock_icon,
          iconColor: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) ? AppColors.textColor : AppColors.primaryRedColor,
          iconSize: 16.w,
          backgroundColor:
              AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) ? AppColors.greyColor : AppColors.secondaryLightRedColor,
          textColor: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) ? AppColors.textColor : AppColors.primaryRedColor,
          padding: EdgeInsets.all(8.h),
        ).toShimmer2(isShow: widget.myAppointmentsViewModel.isMyAppointmentsLoading),
        SizedBox(height: 16.h),
        IntrinsicWidth(
          child: Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Utils.buildImgWithNetwork(
                      url: widget.patientAppointmentHistoryResponseModel.doctorImageURL ??
                          "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                      iconColor: AppColors.transparent,
                      width: 30.h,
                      height: 30.h,
                      fit: BoxFit.fill,
                    ).circle(100.r).toShimmer2(isShow: widget.myAppointmentsViewModel.isMyAppointmentsLoading),
                    SizedBox(width: 8.w),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          (widget.patientAppointmentHistoryResponseModel.doctorNameObj ?? "")
                              .toText14(
                                  isBold: true,
                                  maxlines: 1,
                                  isEnglishOnly: !Utils.isArabicText(widget.patientAppointmentHistoryResponseModel.doctorNameObj ?? ""))
                              .toShimmer2(isShow: widget.myAppointmentsViewModel.isMyAppointmentsLoading),
                          (widget.patientAppointmentHistoryResponseModel.clinicName ?? "")
                              .toText12(maxLine: 1, textOverflow: TextOverflow.ellipsis, isBold: true, color: AppColors.greyTextColor)
                              .toShimmer2(isShow: widget.myAppointmentsViewModel.isMyAppointmentsLoading),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8.h),
                _buildAppointmentActionButton(context, appState),
              ],
            ).paddingAll(16.w),
          ),
        ),
      ],
    );
  }

  /// Builds the appropriate action button based on appointment state and doctor status
  Widget _buildAppointmentActionButton(BuildContext context, AppState appState) {
    final isLoading = widget.myAppointmentsViewModel.isMyAppointmentsLoading;
    final appointment = widget.patientAppointmentHistoryResponseModel;
    final isDoctorActive = appointment.isActiveDoctor ?? true;

    // If doctor is not active, show only View Details button
    if (!isDoctorActive) {
      return _buildViewDetailsButton(context);
    }

    // Doctor is active - check rebooking logic
    final isArrived = AppointmentType.isArrived(appointment);
    final isRebookingNotAllowed = appointment.isClinicReBookingAllowed == false;

    // If arrived and rebooking not allowed, show button without arrow
    if (isArrived && isRebookingNotAllowed) {
      return _buildSingleButton(context, isLoading);
    }

    // Normal flow - show button with arrow
    return _buildButtonWithArrow(context, appState, isLoading);
  }

  /// Builds a single button without arrow (for no rebooking scenarios)
  Widget _buildSingleButton(BuildContext context, bool isLoading) {
    if (isLoading) {
      return Container().toShimmer2(isShow: true, height: 40.h, width: 100.w, radius: 12.r);
    }

    final isArrived = AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel);

    if (isArrived) {
      return getArrivedAppointmentButton(context).toShimmer2(isShow: isLoading);
    }

    return _buildNextActionButton(context, isLoading);
  }

  /// Builds the next action button (Pay Now, Confirm, etc.)
  Widget _buildNextActionButton(BuildContext context, bool isLoading) {
    final appointment = widget.patientAppointmentHistoryResponseModel;

    return CustomButton(
      text: AppointmentType.getNextActionText(appointment.nextAction),
      onPressed: () {
        handleAppointmentNextAction(appointment.nextAction, context);
      },
      backgroundColor: AppointmentType.getNextActionButtonColor(appointment.nextAction).withValues(alpha: 0.15),
      borderColor: AppointmentType.getNextActionButtonColor(appointment.nextAction).withValues(alpha: 0.01),
      textColor: AppointmentType.getNextActionTextColor(appointment.nextAction),
      fontSize: 14.f,
      fontWeight: FontWeight.w600,
      borderRadius: 12.r,
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      height: 40.h,
      icon: AppointmentType.getNextActionIcon(appointment.nextAction),
      iconColor: AppointmentType.getNextActionTextColor(appointment.nextAction),
      iconSize: 14.h,
    ).toShimmer2(isShow: isLoading);
  }

  /// Builds button with arrow (normal flow with navigation arrow)
  Widget _buildButtonWithArrow(BuildContext context, AppState appState, bool isLoading) {
    return Row(
      children: [
        _buildMainActionButton(context, isLoading),
        SizedBox(width: 8.w),
        _buildNavigationArrow(context, appState, isLoading),
      ],
    );
  }

  /// Builds the main action button in the row (left side)
  Widget _buildMainActionButton(BuildContext context, bool isLoading) {
    if (isLoading) {
      return Container().toShimmer2(isShow: true, height: 40.h, width: 100.w, radius: 12.r);
    }

    final isArrived = AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel);

    return Expanded(
      flex: 7,
      child: isArrived ? getArrivedAppointmentButton(context).toShimmer2(isShow: isLoading) : _buildNextActionButton(context, isLoading),
    );
  }

  /// Builds the navigation arrow button (right side)
  Widget _buildNavigationArrow(BuildContext context, AppState appState, bool isLoading) {
    final appointment = widget.patientAppointmentHistoryResponseModel;
    final isArrived = AppointmentType.isArrived(appointment);

    // Check if arrow should be hidden
    final shouldHideArrow = (appointment.isLiveCareAppointment ?? false) ||
        (appointment.isExecludeDoctor ?? false) ||
        !Utils.isClinicAllowedForRebook(appointment.clinicID ?? 0);

    if (shouldHideArrow && isArrived) {
      return SizedBox.shrink();
    }

    return Expanded(
      flex: 2,
      child: Container(
        height: 40.h,
        width: 40.h,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.textColor,
          borderRadius: 10.r,
        ),
        child: Padding(
          padding: EdgeInsets.all(10.h),
          child: Transform.flip(
            flipX: appState.isArabic(),
            child: Utils.buildSvgWithAssets(
              iconColor: AppColors.whiteColor,
              icon: AppAssets.forward_arrow_icon_small,
              width: 36.h,
              height: 36.h,
              fit: BoxFit.contain,
            ),
          ),
        ),
      ).toShimmer2(isShow: isLoading).onPress(() {
        Navigator.of(context)
            .push(
          CustomPageRoute(
            page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: appointment),
          ),
        )
            .then((val) {
          // Can refresh appointments here if needed
        });
      }),
    );
  }

  /// Builds the View Details button (for inactive doctors)
  Widget _buildViewDetailsButton(BuildContext context) {
    return CustomButton(
      text: LocaleKeys.viewDetails.tr(context: context),
      onPressed: () {
        Navigator.of(context)
            .push(
          CustomPageRoute(
            page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
          ),
        )
            .then((_) {
          widget.myAppointmentsViewModel.initAppointmentsViewModel();
          widget.myAppointmentsViewModel.getPatientAppointments(true, false);
        });
      },
      backgroundColor: AppColors.secondaryLightRedColor,
      borderColor: AppColors.secondaryLightRedColor,
      textColor: AppColors.primaryRedColor,
      fontSize: (isFoldable || isTablet) ? 12.f : 14.f,
      fontWeight: FontWeight.w600,
      borderRadius: 12.r,
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      height: isFoldable ? 36.h : 40.h,
    ).toShimmer2(isShow: widget.myAppointmentsViewModel.isMyAppointmentsLoading);
  }

  Widget getArrivedAppointmentButton(BuildContext context) {
    // Check if rebooking is not allowed - show View Details button
    if (widget.patientAppointmentHistoryResponseModel.isClinicReBookingAllowed == false) {
      return CustomButton(
        text: LocaleKeys.viewDetails.tr(context: context),
        onPressed: () {
          Navigator.of(context)
              .push(
            CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ),
          )
              .then((_) {
            widget.myAppointmentsViewModel.initAppointmentsViewModel();
            widget.myAppointmentsViewModel.getPatientAppointments(true, false);
          });
        },
        backgroundColor: AppColors.secondaryLightRedColor,
        borderColor: AppColors.secondaryLightRedColor,
        textColor: AppColors.primaryRedColor,
        fontSize: (isFoldable || isTablet) ? 12.f : 14.f,
        fontWeight: FontWeight.w600,
        borderRadius: 12.r,
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        height: 40.h,
      );
    }

    // Check if clinic allows rebooking or if doctor is excluded
    if ((((widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false) ||
            (widget.patientAppointmentHistoryResponseModel.isExecludeDoctor ?? false) ||
            !Utils.isClinicAllowedForRebook(widget.patientAppointmentHistoryResponseModel.clinicID ?? 0))) &&
        AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)) {
      return CustomButton(
        text: LocaleKeys.viewDetails.tr(context: context),
        onPressed: () {
          Navigator.of(context)
              .push(
            CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ),
          )
              .then((_) {
            widget.myAppointmentsViewModel.initAppointmentsViewModel();
            widget.myAppointmentsViewModel.getPatientAppointments(true, false);
          });
        },
        backgroundColor: AppColors.secondaryLightRedColor,
        borderColor: AppColors.secondaryLightRedColor,
        textColor: AppColors.primaryRedColor,
        fontSize: (isFoldable || isTablet) ? 12.f : 14.f,
        fontWeight: FontWeight.w600,
        borderRadius: 12.r,
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        // height: isTablet || isFoldable ? 46.h : 40.h,
        height: 40.h,
        icon: null,
        iconColor: AppColors.primaryRedColor,
        iconSize: 16.h,
      );
    } else {
      return CustomButton(
        text: LocaleKeys.rebook.tr(context: context),
        onPressed: () {
          widget.onRescheduleTap();
        },
        backgroundColor: AppColors.greyColor,
        borderColor: AppColors.greyColor,
        textColor: AppColors.blackColor,
        fontSize: 14.f,
        fontWeight: FontWeight.w600,
        borderRadius: 12.r,
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        height: 40.h,
        icon: AppAssets.rebook_appointment_icon,
        iconColor: AppColors.blackColor,
        iconSize: 16.h,
      );
    }
  }

  Future<void> handleAppointmentNextAction(nextAction, BuildContext context) async {
    switch (nextAction) {
      case 0:
        // No action needed - go to details
        Navigator.of(context)
            .push(CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ))
            .then((val) {});
        break;
      case 10:
        // Confirm appointment - go to details
        Navigator.of(context)
            .push(CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ))
            .then((val) {});
        break;
      case 15:
        // Pending payment - show waiting modal
        // Ensure timer is running before showing modal
        if (_countdownTimer == null || !_countdownTimer!.isActive) {
          _startCountdownTimer();
        }

        showCommonBottomSheetWithoutHeight(
          context,
          title: LocaleKeys.notice.tr(),
          child: StatefulBuilder(
            builder: (context, setModalState) {
              // Store the modal setState callback
              _modalSetState = setModalState;

              return Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // Message text
                  LocaleKeys.upcomingPaymentPending.tr(context: context).toText14(
                        color: AppColors.textColor,
                        isCenter: true,
                      ),
                  SizedBox(height: 24.h),
                  // Countdown Timer - DD : HH : MM : SS format with labels
                  Directionality(
                      textDirection: ui.TextDirection.ltr,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // Days
                          _buildTimeUnit(
                            _timeRemaining != null ? _timeRemaining!.inDays.toString().padLeft(2, '0') : '00',
                            LocaleKeys.days.tr(context: context),
                          ),
                          _buildTimeSeparator(),
                          // Hours
                          _buildTimeUnit(
                            _timeRemaining != null ? _timeRemaining!.inHours.remainder(24).toString().padLeft(2, '0') : '00',
                            LocaleKeys.hours.tr(context: context),
                          ),
                          _buildTimeSeparator(),
                          // Minutes
                          _buildTimeUnit(
                            _timeRemaining != null ? _timeRemaining!.inMinutes.remainder(60).toString().padLeft(2, '0') : '00',
                            LocaleKeys.minutes.tr(context: context),
                          ),
                          _buildTimeSeparator(),
                          // Seconds
                          _buildTimeUnit(
                            _timeRemaining != null ? _timeRemaining!.inSeconds.remainder(60).toString().padLeft(2, '0') : '00',
                            LocaleKeys.seconds.tr(context: context),
                          ),
                        ],
                      )),
                  SizedBox(height: 24.h),
                  // Green Acknowledge button with checkmark icon
                  CustomButton(
                    text: LocaleKeys.acknowledged.tr(context: context),
                    onPressed: () {
                      _modalSetState = null; // Clear callback when closing
                      Navigator.of(context).pop();
                    },
                    backgroundColor: AppColors.successColor,
                    borderColor: AppColors.successColor,
                    textColor: Colors.white,
                    fontSize: 16.f,
                    fontWeight: FontWeight.w600,
                    borderRadius: 12.r,
                    height: 50.h,
                    icon: AppAssets.checkmark_icon,
                    iconColor: Colors.white,
                  ),
                ],
              );
            },
          ),
          callBackFunc: () {
            _modalSetState = null; // Clear callback when closing
          },
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
        break;
      case 20:
        // Pay now - navigate to payment page
        widget.myAppointmentsViewModel.setIsPatientAppointmentShareLoading(true);
        Navigator.of(context).push(
          CustomPageRoute(
            page: AppointmentPaymentPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
          ),
        );
        break;
      case 50:
        // Confirm livecare - go to details
        Navigator.of(context)
            .push(CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ))
            .then((val) {});
        break;
      case 90:
        // Check-in - go to details
        Navigator.of(context)
            .push(CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ))
            .then((val) {});
        break;
      default:
        // Default - go to details
        Navigator.of(context)
            .push(CustomPageRoute(
              page: AppointmentDetailsPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
            ))
            .then((val) {});
    }
  }
}
