import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.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/route_extensions.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_invoices/models/get_invoices_list_response_model.dart';
import 'package:hmg_patient_app_new/features/refund_request/models/req_models/submit_refund_request_model.dart';
import 'package:hmg_patient_app_new/features/refund_request/refund_request_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/widgets/invoice_list_card.dart';
import 'package:hmg_patient_app_new/presentation/refund_request/refund_history_screen.dart';
import 'package:hmg_patient_app_new/presentation/refund_request/widgets/refund_reason_bottom_sheet.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/radio_list_tile_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/widgets/stepper/stepper_widget.dart';
import 'package:provider/provider.dart';

class RefundRequestCreatePage extends StatefulWidget {
  final GetInvoicesListResponseModel invoice;

  /// 0 = Invoices (default), 1 = HMG Wallet
  final int initialTabIndex;

  const RefundRequestCreatePage({
    super.key,
    required this.invoice,
    this.initialTabIndex = 0,
  });

  @override
  State<RefundRequestCreatePage> createState() => _RefundRequestCreatePageState();
}

class _RefundRequestCreatePageState extends State<RefundRequestCreatePage> {
  late RefundRequestViewModel _refundRequestViewModel;
  late AppState _appState;

  final TextEditingController _ibanController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final FocusNode _ibanFocusNode = FocusNode();
  final FocusNode _descriptionFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _appState = getIt.get<AppState>();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refundRequestViewModel = context.read<RefundRequestViewModel>();
      _ibanController.addListener(() => _refundRequestViewModel.triggerRebuild());
      _descriptionController.addListener(() => _refundRequestViewModel.triggerRebuild());
      _loadInvoiceDetails();
    });
  }

  @override
  void dispose() {
    _ibanController.dispose();
    _descriptionController.dispose();
    _ibanFocusNode.dispose();
    _descriptionFocusNode.dispose();
    _refundRequestViewModel.resetState();
    super.dispose();
  }

  void _loadInvoiceDetails() {
    final invoiceNo = widget.invoice.invoiceNo;
    final projectId = widget.invoice.projectId;
    if (invoiceNo == null || projectId == null) return;

    _refundRequestViewModel.getRefundableInvoicesDetails(
      invoiceNo: invoiceNo,
      projectId: projectId,
      onSuccess: (details) {
        final procedures = details.refundableInvoiceDetailsItems
            .map((item) => RefundableProcedure(
                  procedureId: item.lineItemNo ?? 0,
                  procedureName: item.procedureName ?? '',
                  patientPaidAmount: item.patientPaidAmount ?? 0.0,
                  apiLineItemNo: item.lineItemNo,
                  apiProcedureId: item.procedureId,
                ))
            .toList();
        _refundRequestViewModel.setProcedures(procedures, needsITGApproval: details.needITGApproval ?? false);
      },
    );
  }

  // ── Stepper ───────────────────────────────────────────────────────────────

  Widget _buildStepper(RefundRequestViewModel vm) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: LayoutBuilder(
        builder: (context, constraints) {
          // StepperWidget appends SizedBox(width: 8.h) after itself
          final itemWidth = (constraints.maxWidth - 2 * 8.h) / 2;
          return Row(
            children: List.generate(2, (index) {
              final isActive = index <= vm.currentStep;
              final isThumb = index == vm.currentStep;
              return StepperWidget(
                itemWidth,
                isActive ? AppColors.primaryRedColor : AppColors.greyColor,
                isThumb,
                6.h,
              );
            }),
          );
        },
      ),
    );
  }

  // ── Step 1 — exactly mirrors RechargeWalletPage hospital row ─────────────

  Widget _buildStep1Content(RefundRequestViewModel vm) {
    return Consumer<RefundRequestViewModel>(
      builder: (context, refundVM, _) {
        final isArabic = _appState.isArabic();
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            LocaleKeys.selectProcedures.tr(context: context).toText20(isBold: true),
            SizedBox(height: 24.h),
            if (vm.isProceduresLoading)
              ListView.separated(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                separatorBuilder: (context, index) => SizedBox(height: 16.h),
                itemCount: 4,
                itemBuilder: (_, index) => Container(
                  height: 40.h,
                  margin: EdgeInsets.only(bottom: 24.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor,
                    borderRadius: 16.h,
                  ),
                ).toShimmer2(isShow: true, radius: 16.r),
              )
            else if (vm.procedures.isEmpty)
              Center(
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 24.h),
                  child: LocaleKeys.noProceduresAvailableForRefund.tr().toText14(color: AppColors.greyTextColor),
                ),
              )
            else
              AnimationLimiter(
                child: Container(
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.h, hasShadow: false),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Select All row
                      Material(
                        color: Colors.transparent,
                        child: InkWell(
                          onTap: () => _refundRequestViewModel.toggleSelectAll(),
                          child: Padding(
                            padding: EdgeInsets.all(16.h),
                            child: Row(
                              children: [
                                SizedBox(
                                  width: 24.w,
                                  height: 24.w,
                                  child: Transform.scale(
                                    scale: 24.w / 22,
                                    child: Checkbox(
                                      value: vm.isAllSelected,
                                      onChanged: (_) => _refundRequestViewModel.toggleSelectAll(),
                                      activeColor: AppColors.primaryRedColor,
                                      side: BorderSide(color: AppColors.checkBoxBorderColor, width: 1),
                                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                      visualDensity: VisualDensity.compact,
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.r)),
                                    ),
                                  ),
                                ),
                                SizedBox(width: 8.w),
                                LocaleKeys.selectAll.tr(context: context).toText16(isBold: true),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1).paddingSymmetrical(16.w, 0.w),
                      ...List.generate(
                        vm.procedures.length,
                        (index) => _buildProcedureCard(vm.procedures[index], index, vm.procedures.length),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        );
      },
    );
  }

  // ── Step 2 — payment method selection ────────────────────────────────────

  Widget _buildStep2Content(RefundRequestViewModel vm) {
    final paymentOptions = [
      RefundTabType.hmgWallet,
      RefundTabType.invoices,
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        LocaleKeys.selectRefundMethod.tr(context: context).toText20(isBold: true),
        SizedBox(height: 24.h),
        Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 24.h,
            hasShadow: false,
          ),
          child: ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: paymentOptions.length,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              final type = paymentOptions[index];
              return Column(
                children: [
                  RadioListTileWidget<RefundTabType>(
                    value: type,
                    groupValue: vm.selectedPaymentMethod,
                    title: type.toDisplayString(),
                    onChanged: (value) {
                      if (value != null) vm.setPaymentMethod(value);
                    },
                  ),
                  if (index != paymentOptions.length - 1)
                    Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1).paddingSymmetrical(16.w, 0.w),
                ],
              );
            },
          ),
        ),
        if (vm.selectedPaymentMethod == RefundTabType.invoices) ...[
          SizedBox(height: 16.h),
          _buildBankInputDetails(vm),
        ],
      ],
    );
  }

  // ── Bank Transfer Input ───────────────────────────────────────────────────

  Widget _buildBankInputDetails(RefundRequestViewModel vm) {
    final hasError = vm.ibanError != null || vm.descriptionError != null;
    return Container(
      padding: EdgeInsets.all(16.h),
      decoration: BoxDecoration(
        color: AppColors.whiteColor,
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(
          color: hasError ? AppColors.primaryRedBorderColor : Colors.transparent,
          width: 1,
        ),
      ),
      child: Column(
        children: [
          TextInputWidget(
            labelText: LocaleKeys.addIbanDetails.tr(),
            hintText: "SA0000000000000000000000",
            controller: _ibanController,
            focusNode: _ibanFocusNode,
            autoFocus: false,
            keyboardType: TextInputType.text,
            isEnable: true,
            isReadOnly: false,
            prefix: null,
            isBorderAllowed: false,
            isAllowLeadingIcon: true,
            fontSize: 14.f,
            isCountryDropDown: false,
            leadingIcon: AppAssets.bankIcon,
            fontFamily: "Poppins",
            hasError: false,
            errorMessage: vm.ibanError,
            onChange: (value) {
              vm.clearIbanError();
            },
            onSubmitted: (value) {
              _descriptionFocusNode.requestFocus();
            },
          ),
          Divider(color: AppColors.bottomNAVBorder, thickness: 1).withVerticalPadding(16.h),
          TextInputWidget(
            labelText: LocaleKeys.description.tr(),
            hintText: LocaleKeys.enterDescription.tr(),
            controller: _descriptionController,
            focusNode: _descriptionFocusNode,
            autoFocus: false,
            keyboardType: TextInputType.text,
            isEnable: true,
            isReadOnly: false,
            prefix: null,
            isBorderAllowed: false,
            isAllowLeadingIcon: true,
            fontSize: 14.f,
            isCountryDropDown: false,
            leadingIcon: AppAssets.descriptionIcon,
            fontFamily: "Poppins",
            hasError: false,
            errorMessage: vm.descriptionError,
            onChange: (value) {
              vm.clearDescriptionError();
            },
          ),
        ],
      ),
    );
  }

  // ── Step 2 — procedure checkboxes ─────────────────────────────────────────

  Widget _buildProcedureCard(RefundableProcedure procedure, int index, int length) {
    final isArabic = _appState.isArabic();
    final name = isArabic && procedure.procedureNameN != null ? procedure.procedureNameN! : procedure.procedureName;

    return AnimationConfiguration.staggeredList(
      position: index,
      duration: const Duration(milliseconds: 400),
      child: SlideAnimation(
        verticalOffset: 50.0,
        child: FadeInAnimation(
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 250),
            curve: Curves.easeInOut,
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () => _refundRequestViewModel.toggleProcedureSelection(procedure),
                child: Padding(
                  padding: EdgeInsets.all(16.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(
                            width: 24.w,
                            height: 24.w,
                            child: Transform.scale(
                              scale: 24.w / 22,
                              child: Checkbox(
                                value: procedure.isSelected,
                                onChanged: (_) => _refundRequestViewModel.toggleProcedureSelection(procedure),
                                activeColor: AppColors.primaryRedColor,
                                side: BorderSide(color: AppColors.checkBoxBorderColor, width: 1),
                                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                visualDensity: VisualDensity.compact,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(4.r),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Expanded(child: name.toText16(isBold: true)),
                          SizedBox(width: 8.w),
                          Utils.getPaymentAmountWithSymbol(
                            procedure.patientPaidAmount.toStringAsFixed(2).toText20(
                                  isBold: true,
                                  isEnglishOnly: true,
                                  color: AppColors.textColor,
                                ),
                            AppColors.textColor,
                            10.f,
                            isSaudiCurrency: true,
                          ),
                        ],
                      ),
                      if (procedure.isSelected) ...[
                        InkWell(
                          onTap: () => showRefundReasonBottomSheet(
                            context,
                            selectedReason: procedure.refundReason,
                            onDone: (reason) => _refundRequestViewModel.setRefundReasonForProcedure(procedure, reason),
                          ),
                          child: Padding(
                            padding: EdgeInsets.only(top: 16.h),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      LocaleKeys.refundReason.tr(context: context).toText12(color: AppColors.greyTextColor, isBold: true),
                                      (procedure.refundReason ?? LocaleKeys.selectRefundReason.tr(context: context))
                                          .toText14(color: AppColors.textColor, isBold: true),
                                    ],
                                  ),
                                ),
                                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                              ],
                            ),
                          ),
                        ),
                      ],
                      if (index != length - 1) ...[
                        Divider(color: AppColors.bottomNAVBorder, height: 1, thickness: 1).paddingOnly(top: 16.h),
                      ]
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // ── Bottom bar ────────────────────────────────────────────────────────────

  Widget _buildBottomBar(RefundRequestViewModel refundRequestViewModel) {
    final isStep2 = refundRequestViewModel.currentStep == 1;
    final isWallet = refundRequestViewModel.selectedTab == RefundTabType.hmgWallet;

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (!isWallet && refundRequestViewModel.selectedProcedures.isNotEmpty) ...[
            Padding(
              padding: EdgeInsets.fromLTRB(24.w, 16.h, 24.w, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  LocaleKeys.totalAmount.tr().toText18(color: AppColors.textColor, isBold: true),
                  Utils.getPaymentAmountWithSymbol(
                    refundRequestViewModel.totalRefundableAmount.toStringAsFixed(2).toText24(
                          isBold: true,
                          isEnglishOnly: true,
                          color: AppColors.textColor,
                        ),
                    AppColors.textColorLight,
                    14,
                    isSaudiCurrency: true,
                  ),
                ],
              ),
            ),
          ],
          CustomButton(
            icon: isStep2 ? AppAssets.refundIcon : null,
            text: isStep2 ? LocaleKeys.submit.tr(context: context) : LocaleKeys.next.tr(context: context),
            onPressed: () {
              if (!isStep2) {
                if (refundRequestViewModel.selectedProcedures.isNotEmpty) refundRequestViewModel.nextStep();
              } else {
                final isBankTransfer = refundRequestViewModel.selectedPaymentMethod == RefundTabType.invoices;
                if (isBankTransfer) {
                  final isValid = refundRequestViewModel.validateBankTransferForm(
                    iban: _ibanController.text,
                    description: _descriptionController.text,
                  );
                  if (!isValid) return;
                }
                _handleInvoiceRefundRequestSubmit(refundRequestViewModel);
              }
            },
            isDisabled: isStep2
                ? (refundRequestViewModel.selectedPaymentMethod == null ||
                    (refundRequestViewModel.selectedPaymentMethod == RefundTabType.invoices &&
                        (_ibanController.text.trim().isEmpty || _descriptionController.text.trim().isEmpty)))
                : (refundRequestViewModel.selectedProcedures.isEmpty || !refundRequestViewModel.allSelectedProceduresHaveReasons),
          ).paddingSymmetrical(24.h, 24.h),
        ],
      ),
    );
  }

  // ── HMG Wallet placeholder ─────────────────────────────────────────────────

  Widget buildInvoiceCard() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      child: InvoiceListCard(onTap: null, getInvoicesListResponseModel: widget.invoice),
    );
  }

  // ── Submit ────────────────────────────────────────────────────────────────

  void _handleInvoiceRefundRequestSubmit(RefundRequestViewModel vm) {
    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.notice.tr(context: context),
      child: Utils.getWarningWidget(
        loadingText: LocaleKeys.confirmSubmitRequest.tr(context: context),
        isShowActionButtons: true,
        onCancelTap: () => Navigator.pop(context),
        onConfirmTap: () async {
          Navigator.pop(context);
          LoaderBottomSheet.showLoader();

          final isBankTransfer = vm.selectedPaymentMethod == RefundTabType.invoices;
          final invoice = widget.invoice;
          final userPayload = _appState.getAuthenticatedUser();
          final patientId = userPayload!.patientId;
          final patientName = "${userPayload.firstName} ${userPayload.lastName}";
          final patientMobileNumber = "${userPayload.mobileNumber}";
          final patientNationalId = userPayload.patientIdentificationNo.toString();
          final request = SubmitRefundRequestModel(
            projectId: invoice.projectId ?? 0,
            refundType: '1',
            isRefundFastTrack: vm.needITGApproval,
            refundProject: invoice.projectName ?? '',
            refundProjectId: invoice.projectId ?? 0,
            refundPatientId: patientId.toString(),
            refundPatientName: patientName,
            refundNationalId: patientNationalId,
            patientMobileNumber: patientMobileNumber,
            refundInvoiceNo: (invoice.invoiceNo ?? 0).toString(),
            refundAppointmentNo: (invoice.appointmentNo ?? 0).toString(),
            refundDoctorId: invoice.doctorId ?? 0,
            refundDoctorName: invoice.doctorName ?? '',
            refundClinicId: invoice.clinicId ?? 0,
            refundClinicName: invoice.clinicName ?? '',
            refundDestination: isBankTransfer ? '2' : '1',
            refundIban: isBankTransfer ? _ibanController.text.trim() : '',
            refundRemarks: isBankTransfer ? _descriptionController.text.trim() : '',
            refundTotalAmount: vm.totalRefundableAmount,
            refundProceduresList: vm.selectedProcedures
                .map((p) => SubmitRefundProcedureItem(
                      lineItemNo: p.apiLineItemNo ?? 0,
                      procedureId: p.apiProcedureId ?? '',
                      procedureName: p.procedureName,
                      patientPaidAmount: p.patientPaidAmount,
                      refundReason: p.refundReason ?? '',
                    ))
                .toList(),
          );

          await vm.submitInvoiceRefundRequest(
            request: request,
            onSuccess: (response) {
              LoaderBottomSheet.hideLoader();
              _showSuccessBottomSheet(response.refNo ?? '');
            },
            onError: (err) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(
                context,
                child: Utils.getErrorWidget(loadingText: err),
                callBackFunc: () {},
              );
            },
          );
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  void _showSuccessBottomSheet(String refNo) {
    showCommonBottomSheetWithoutHeight(
      context,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            Utils.getSuccessWidget(loadingText: LocaleKeys.requestSubmittedSuccessfully.tr(context: context)),
            if (refNo.isNotEmpty) ...[
              SizedBox(height: 8.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  LocaleKeys.hereIsYourRequestNumber.tr().toText16(
                        color: AppColors.textColorLight,
                      ),
                  SizedBox(width: 6.w),
                  refNo.toText18(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                ],
              ).paddingSymmetrical(24.w, 0),
            ],
            SizedBox(height: 24.h),
            Row(
              children: [
                Expanded(
                  child: CustomButton(
                    height: 56.h,
                    text: LocaleKeys.ok.tr(),
                    onPressed: () {
                      Navigator.pop(context); // pop success sheet
                      Navigator.pop(context); // pop refund page
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: RefundHistoryScreen(
                            refundType: 1, // 2 for wallet, 1 for invoice
                          ),
                        ),
                      );
                    },
                    textColor: AppColors.whiteColor,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      isCloseButtonVisible: false,
      isDismissible: false,
      isFullScreen: false,
      isAutoDismiss: false,
    );
  }

// ── Build ─────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    return Consumer<RefundRequestViewModel>(
      builder: (context, vm, _) {
        return Scaffold(
          backgroundColor: AppColors.bgScaffoldColor,
          body: Column(
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.requestRefund.tr(context: context),
                  leadingCallback: () {
                    final refundRequestViewModel = context.read<RefundRequestViewModel>();
                    if (refundRequestViewModel.currentStep > 0) {
                      refundRequestViewModel.previousStep();
                    } else {
                      context.pop();
                    }
                  },
                  requests: () => Navigator.of(context).push(CustomPageRoute(
                      page: RefundHistoryScreen(
                    refundType: 1, // 1 for invoice, 2 for wallet
                  ))),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.only(bottom: 32.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Stepper (invoices tab only)
                        if (vm.selectedTab == RefundTabType.invoices) ...[
                          buildInvoiceCard(),
                          _buildStepper(vm),
                          SizedBox(height: 16.h),
                        ],
                        // Content
                        AnimatedSwitcher(
                          duration: const Duration(milliseconds: 350),
                          transitionBuilder: (child, animation) => FadeTransition(
                            opacity: animation,
                            child: SlideTransition(
                              position: Tween<Offset>(
                                begin: const Offset(0.05, 0),
                                end: Offset.zero,
                              ).animate(animation),
                              child: child,
                            ),
                          ),
                          child: vm.currentStep == 0
                              ? KeyedSubtree(
                                  key: const ValueKey('step1'),
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                                    child: _buildStep1Content(vm),
                                  ),
                                )
                              : KeyedSubtree(
                                  key: const ValueKey('step2'),
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                                    child: _buildStep2Content(vm),
                                  ),
                                ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              _buildBottomBar(vm),
            ],
          ),
        );
      },
    );
  }
}
