// ignore_for_file: unused_element, use_build_context_synchronously

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:confetti/confetti.dart';
import 'package:hyper_local/utils/extensions.dart';
import 'package:hyper_local/utils/widgets/custom_image_container.dart';
import 'package:location/location.dart';
import 'package:latlong2/latlong.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hyper_local/utils/widgets/empty_state_widget.dart';
import 'package:hyper_local/config/app_images.dart';
import '../../../../config/colors.dart';
import '../../../../config/helper.dart';
import '../../../../utils/currency_formatter.dart';
import '../../../../utils/widgets/custom_text.dart';
import '../../../../utils/widgets/custom_appbar_without_navbar.dart';
import '../../../../utils/widgets/custom_scaffold.dart';
import '../../../../utils/widgets/loading_widget.dart';
import '../../../../utils/widgets/toast_message.dart';
import '../../../system_settings/bloc/system_settings_bloc.dart';
import '../../../system_settings/bloc/system_settings_event.dart';
import '../../../system_settings/bloc/system_settings_state.dart';
import '../../model/available_orders.dart';
import '../../bloc/items_collected_bloc/items_collected_bloc.dart';
import '../../bloc/items_collected_bloc/items_collected_event.dart';
import '../../bloc/items_collected_bloc/items_collected_state.dart';
import '../../bloc/order_details_bloc/order_details_bloc.dart';
import '../../bloc/order_details_bloc/order_details_event.dart';
import '../../bloc/order_details_bloc/order_details_state.dart';
import '../../bloc/available_orders_bloc/available_orders_bloc.dart';
import '../../bloc/available_orders_bloc/available_orders_event.dart';
import '../../bloc/my_orders_bloc/my_orders_bloc.dart';
import '../../bloc/my_orders_bloc/my_orders_event.dart';
import '../../../../utils/widgets/custom_button.dart';
import '../../../../utils/widgets/reusable_bottom_sheet.dart';
import '../../../../utils/widgets/custom_card.dart';
import '../../widgets/orderdetails_widgets/index.dart' hide PaymentMethodCard, OrderNoteCard;
import '../../../../router/app_routes.dart';
import 'package:hyper_local/l10n/app_localizations.dart';
import '../map/widgets/unified_map_widget.dart';
import '../map/store_pickup_route/services/map_service.dart';
import '../map/store_pickup_route/services/navigation_service.dart';
import 'widgets/payment_method_card.dart';
import 'widgets/order_note_card.dart';
import 'widgets/order_items_section.dart';
import 'widgets/earnings_details_section.dart';
import 'widgets/store_details_section.dart';
import 'widgets/shipping_details_section.dart';
import '../../repo/order_actions_repo.dart';
import '../../services/order_service.dart';
import '../../services/dialog_service.dart';
import '../../../../utils/services/phone_service.dart';
import '../../../../utils/services/ui_helper_service.dart';
import '../../services/item_card_service.dart';

class OrderDetailsPage extends StatefulWidget {
  final int orderId;
  final bool from;
  final int? sourceTab; // 0 = Available Orders, 1 = My Orders
  final bool? arrivalConfirmed; // Whether arrival has been confirmed
  final bool isBottomSheet; // Whether it is shown inside a bottom sheet

  const OrderDetailsPage({
    super.key,
    required this.orderId,
    this.from = false,
    this.sourceTab,
    this.arrivalConfirmed,
    this.isBottomSheet = false,
  });

  @override
  State<OrderDetailsPage> createState() => _OrderDetailsPageState();
}

class _OrderDetailsPageState extends State<OrderDetailsPage> with TickerProviderStateMixin {
  Orders? _fetchedOrder;

  // Local state sets for tracking item status
  final Set<String> _collectedItems = {};
  final Set<String> _deliveredItems = {};
  final Set<String> _otpVerifiedItems = {};

  // UI state variables
  bool _isItemsExpanded = true;
  bool _isDeliveryExpanded = false;
  bool _isStoreDetailsExpanded = false;
  bool _isEarningsExpanded = false;
  bool _codPopupShown = false;
  final Set<String> _processingItemIds = {};
  final Set<int> _collectingStoreIds = {};
  bool _isCollectingAll = false;
  bool _isApiFailed = false;
  bool _isCancellingOrder = false;
  bool _isCancellingDelivery = false;

  // Confetti controller for celebration animation
  late ConfettiController _confettiController;

  // Track if confetti has been shown for this order
  bool _hasShownConfetti = false;

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'out_for_delivery':
        return Colors.orange;
      case 'assigned':
        return Colors.blue;
      case 'preparing':
        return Colors.purple;
      case 'ready':
        return Colors.green;
      case 'delivered':
        return Colors.green;
      default:
        return Colors.grey;
    }
  }

  String _capitalizeStatus(String status) {
    if (status.isEmpty) return '';
    return status
        .split('_')
        .map((word) => word.isEmpty ? '' : '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}')
        .join(' ');
  }

  String _getDisplayStatus(String status) {
    // Check if all items are delivered with verified OTP

    // If status is delivered and OTP is verified, don't show pending
    if (status.toLowerCase() == 'delivered') {
      return 'delivered';
    }

    // If status is pending and no items require OTP, show as collected
    if (status.toLowerCase() == 'pending') {
      return 'collected'; // Show as collected instead of pending
    }

    return status;
  }

  bool _areAllItemsDeliveredWithOtp() {
    final order = _fetchedOrder;
    if (order?.items == null || order!.items!.isEmpty) return false;

    for (var item in order.items!) {
      if (item.status?.toLowerCase() != 'delivered' || item.otpVerified != 1) {
        return false;
      }
    }
    return true;
  }

  bool _areAllItemsDelivered() {
    return OrderService.areAllItemsDelivered(_fetchedOrder);
  }

  @override
  void initState() {
    super.initState();
    _confettiController = ConfettiController(duration: const Duration(seconds: 3));

    // Reset confetti flag for new order
    _hasShownConfetti = false;

    // Initialize arrival confirmation status from widget parameter
    // Fetch system system_settings for currency symbol
    context.read<SystemSettingsBloc>().add(FetchSystemSettings());

    // Fetch order details from API
    context.read<OrderDetailsBloc>().add(FetchOrderDetails(widget.orderId));

    // Remove the post-frame callback that was causing state conflicts
    // WidgetsBinding.instance.addPostFrameCallback((_) {

    //   _initializeLocalStateFromApi();
    // });
  }

  @override
  void dispose() {
    _confettiController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // This method is called when the widget's dependencies change
    // It's a good place to refresh data when navigating back to this page

    // Only refresh if we don't have order data
    // Don't refresh if we already have the latest state to preserve bloc updates
    if (_fetchedOrder == null) {
      _refreshOrderDataIfNeeded();
    } else {}
  }

  // Method to refresh order data when needed (e.g., when navigating back)
  void _refreshOrderDataIfNeeded() {
    // Only refresh if we have an order and it's been a while since last refresh
    if (_fetchedOrder != null) {
      context.read<OrderDetailsBloc>().add(FetchOrderDetails(widget.orderId));
    }
  }

  // Method to manually refresh order data
  void _refreshOrderData() {
    // Check if current bloc state has reachedDestination items that we need to preserve
    final currentState = context.read<OrderDetailsBloc>().state;
    Map<String, bool> reachedDestinationItems = {};

    if (currentState.status == ApiStatus.success && currentState.order != null) {
      // Preserve reachedDestination status from current bloc state
      for (var item in currentState.order!.items ?? []) {
        if (item.reachedDestination == true) {
          reachedDestinationItems[item.id.toString()] = true;
        }
      }
    }

    // Clear local state first
    setState(() {
      _deliveredItems.clear();
      _otpVerifiedItems.clear();
      _collectedItems.clear();
    });

    // Fetch fresh data from API
    context.read<OrderDetailsBloc>().add(FetchOrderDetails(widget.orderId));

    // After API response, restore reachedDestination status
    if (reachedDestinationItems.isNotEmpty) {}
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<SystemSettingsBloc, SystemSettingsState>(
      listener: (context, state) {
        if (state.fetchStatus == ApiStatus.success) {
          // Trigger a rebuild to update currency symbols
          setState(() {});
        }
      },
      child: BlocConsumer<ItemsCollectedBloc, ItemsCollectedState>(
        listener: (context, state) {
          if (state.status == ApiStatus.success) {
            String processedItemId = state.itemId;

            setState(() {
              _processingItemIds.remove(processedItemId);

              // Always add to collected items to hide security icon for OTP items
              _collectedItems.add(processedItemId);

              // Add to delivered items if this is delivery mode and order status is not assigned
              // OR if order status is "out_for_delivery"
              if ((widget.from && _fetchedOrder?.status?.toLowerCase() != 'assigned') ||
                  _fetchedOrder?.status?.toLowerCase() == 'out_for_delivery') {
                _deliveredItems.add(processedItemId);
              }

              // Update the local order data immediately for this item
              if (_fetchedOrder?.items != null) {
                List<Items> updatedItems =
                    _fetchedOrder!.items!.map((item) {
                      if (item.id.toString() == processedItemId) {
                        String newStatus = state.isDelivery ? 'delivered' : 'collected';
                        return item.copyWith(status: newStatus);
                      }
                      return item;
                    }).toList();

                _fetchedOrder = _fetchedOrder!.copyWith(items: updatedItems);
              }

              // Remove from _collectingStoreIds if no more items are in queue for this store
              final item = _fetchedOrder?.items?.firstWhere(
                (i) => i.id.toString() == processedItemId,
                orElse: () => Items(),
              );
              if (item != null && item.storeId != null) {
                final hasMoreItemsInQueue =
                    _fetchedOrder?.items?.any(
                      (i) => i.storeId == item.storeId && _processingItemIds.contains(i.id.toString()),
                    ) ??
                    false;
                if (!hasMoreItemsInQueue) {
                  _collectingStoreIds.remove(item.storeId);
                }
              }

              // If this was the last item in "collect all", reset the flag
              if (_isCollectingAll && (_areAllItemsCollected() || _processingItemIds.isEmpty)) {
                _isCollectingAll = false;
              }
            });

            // Dispatch FetchOrderDetails as backup
            context.read<OrderDetailsBloc>().add(FetchOrderDetails(widget.orderId));

            // Show toast or auto-close bottom sheet if all items are collected
            if (!state.isDelivery && _areAllItemsCollected()) {
              ToastManager.show(
                context: context,
                message: AppLocalizations.of(context)!.allItemsCollectedSuccessfully,
                type: ToastType.success,
              );

              if (widget.isBottomSheet) {
                Future.delayed(const Duration(milliseconds: 500), () {
                  if (mounted) {
                    Navigator.of(context).pop();
                  }
                });
              }
            } else {
              String successMessage =
                  state.isDelivery
                      ? AppLocalizations.of(context)!.itemDeliveredSuccessfully
                      : AppLocalizations.of(context)!.itemCollectedSuccessfully;

              // Only show individual toasts if not collecting all
              if (!_isCollectingAll) {
                ToastManager.show(context: context, message: successMessage, type: ToastType.success);
              }
            }
          } else if (state.status == ApiStatus.failed) {
            setState(() {
              _processingItemIds.remove(state.itemId);

              // Remove from _collectingStoreIds if no more items are in queue for this store
              final item = _fetchedOrder?.items?.firstWhere(
                (i) => i.id.toString() == state.itemId,
                orElse: () => Items(),
              );
              if (item != null && item.storeId != null) {
                final hasMoreItemsInQueue =
                    _fetchedOrder?.items?.any(
                      (i) => i.storeId == item.storeId && _processingItemIds.contains(i.id.toString()),
                    ) ??
                    false;
                if (!hasMoreItemsInQueue) {
                  _collectingStoreIds.remove(item.storeId);
                }
              }

              if (_isCollectingAll && _processingItemIds.isEmpty) {
                _isCollectingAll = false;
              }
            });

            ToastManager.show(context: context, message: state.message, type: ToastType.error);
          }
        },
        builder: (context, itemsCollectedState) {
          return BlocConsumer<OrderDetailsBloc, OrderDetailsState>(
            listener: (context, state) {
              if (state.status == ApiStatus.success && state.order != null) {
                // Check if we need to restore reachedDestination status from previous state
                setState(() {
                  _isApiFailed = false;
                  _fetchedOrder = state.order;

                  // Reset confetti flag for new order data
                  if (_fetchedOrder?.id != widget.orderId) {
                    _hasShownConfetti = false;
                  }

                  // Update local state based on API response
                  if (_fetchedOrder?.items != null) {
                    for (var item in _fetchedOrder!.items!) {
                      // Update local state based on API status
                      if (item.id != null) {
                        String itemId = item.id.toString();

                        // If item is delivered according to API, add to delivered items
                        if (item.status?.toLowerCase() == 'delivered') {
                          _deliveredItems.add(itemId);
                        }

                        // If item is collected according to API, add to collected items
                        if (item.status?.toLowerCase() == 'collected' || item.status?.toLowerCase() == 'delivered') {
                          _collectedItems.add(itemId);
                        }

                        // If item has OTP verified according to API, add to OTP verified items
                        if (item.otpVerified == 1) {
                          _otpVerifiedItems.add(itemId);
                        }
                      }
                    }
                  }
                });
              } else if (state.status == ApiStatus.failed) {
                setState(() {
                  _isApiFailed = true;
                });
              }
            },
            builder: (context, state) {
              // Use fetched order data with restored reachedDestination values
              final order = _fetchedOrder;

              if (order == null) {
                return CustomScaffold(
                  appBar:
                      widget.isBottomSheet
                          ? null
                          : CustomAppBar(
                            title: AppLocalizations.of(context)!.orderDetails,
                            showRefreshButton: true,
                            showThemeToggle: false,
                            onRefreshPressed: () {
                              if (_fetchedOrder == null) {
                                _refreshOrderData();
                              } else {
                                ToastManager.show(
                                  context: context,
                                  message: 'Order data is already up to date',
                                  type: ToastType.info,
                                );
                              }
                            },
                          ),
                  body: Column(
                    children: [
                      if (widget.isBottomSheet)
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 8.h),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              CustomText(
                                text: AppLocalizations.of(context)!.orderDetails,
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                              IconButton(
                                icon: Icon(Icons.close, color: Theme.of(context).colorScheme.onSurface, size: 24.sp),
                                onPressed: () => Navigator.pop(context),
                              ),
                            ],
                          ),
                        ),
                      Expanded(
                        child: Center(
                          child:
                              _isApiFailed
                                  ? ErrorStateWidget(
                                    onRetry: () {
                                      context.read<OrderDetailsBloc>().add(FetchOrderDetails(widget.orderId));
                                    },
                                  )
                                  : const LoadingWidget(),
                        ),
                      ),
                    ],
                  ),
                );
              }

              return CustomScaffold(
                appBar:
                    widget.isBottomSheet
                        ? null
                        : CustomAppBar(
                          titleWidget: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              CustomText(
                                text: AppLocalizations.of(context)!.orderDetails,
                                fontSize: sz(18, seprateTabletSize: 14),
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                              SizedBox(height: 2.h),
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  CustomText(
                                    text: '${AppLocalizations.of(context)!.orderId} #${order.id}',
                                    fontSize: sz(13, seprateTabletSize: 11),
                                    fontWeight: FontWeight.w600,
                                    color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6),
                                  ),
                                  SizedBox(width: 6.w),
                                  Icon(
                                    (order.status?.toLowerCase() == 'delivered')
                                        ? Icons.check_circle
                                        : Icons.access_time,
                                    color: _getStatusColor(order.status ?? ''),
                                    size: sz(14, seprateTabletSize: 12).sp,
                                  ),
                                  SizedBox(width: 4.w),
                                  CustomText(
                                    text: _capitalizeStatus(_getDisplayStatus(order.status ?? '')),
                                    fontSize: sz(13, seprateTabletSize: 11),
                                    fontWeight: FontWeight.bold,
                                    color: _getStatusColor(order.status ?? ''),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          additionalActions: [
                            if (!_isOrderCancelled() && _hasCancellableItems())
                              GestureDetector(
                                onTap: () async {
                                  final location = Location();
                                  LocationData? currentLocationData;
                                  try {
                                    currentLocationData = await location.getLocation();
                                  } catch (_) {}

                                  if (currentLocationData == null ||
                                      currentLocationData.latitude == null ||
                                      currentLocationData.longitude == null) {
                                    return;
                                  }

                                  final currentLatLng = LatLng(
                                    currentLocationData.latitude!,
                                    currentLocationData.longitude!,
                                  );

                                  final status = order.status?.toLowerCase() ?? 'assigned';
                                  final bool isPostPickup =
                                      status == 'out_for_delivery' || status == 'collected' || status == 'delivered';

                                  if (!isPostPickup) {
                                    final stores = MapService.getFilteredStores(order.deliveryRoute?.routeDetails);
                                    NavigationService.openGoogleMapsToStores(currentLatLng, stores);
                                  } else {
                                    NavigationService.openGoogleMapsToShippingAddress(
                                      currentLatLng,
                                      order.shippingAddress1,
                                      order.shippingAddress2,
                                    );
                                  }
                                },
                                child: const CustomImageContainer(
                                  imagePath: AppImages.googleMap,
                                  height: 50,
                                  width: 50,
                                ),
                              ),

                            const SizedBox(width: 10),
                          ],
                        ),
                body: Column(
                  children: [
                    if (widget.isBottomSheet)
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  CustomText(
                                    text: AppLocalizations.of(context)!.orderDetails,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                    color: Theme.of(context).colorScheme.onSurface,
                                  ),
                                  SizedBox(height: 2.h),
                                  Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      CustomText(
                                        text: '${AppLocalizations.of(context)!.orderId} #${order.id}',
                                        fontSize: sz(13, seprateTabletSize: 11),
                                        fontWeight: FontWeight.w600,
                                        color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6),
                                      ),
                                      SizedBox(width: 6.w),
                                      Icon(
                                        (order.status?.toLowerCase() == 'delivered')
                                            ? Icons.check_circle
                                            : Icons.access_time,
                                        color: _getStatusColor(order.status ?? ''),
                                        size: sz(14, seprateTabletSize: 12).sp,
                                      ),
                                      SizedBox(width: 4.w),
                                      CustomText(
                                        text: _capitalizeStatus(_getDisplayStatus(order.status ?? '')),
                                        fontSize: sz(13, seprateTabletSize: 11),
                                        fontWeight: FontWeight.bold,
                                        color: _getStatusColor(order.status ?? ''),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            IconButton(
                              icon: Icon(Icons.close, color: Theme.of(context).colorScheme.onSurface, size: 24.sp),
                              onPressed: () => Navigator.pop(context),
                            ),
                          ],
                        ),
                      ),
                    Expanded(
                      child: Stack(
                        children: [
                          RefreshIndicator(
                            onRefresh: () async {
                              final settingsCompleter = Completer<void>();
                              final detailsCompleter = Completer<void>();
                              // Fetch system system_settings for currency symbol
                              context.read<SystemSettingsBloc>().add(FetchSystemSettings(completer: settingsCompleter));

                              // Fetch order details from API
                              context.read<OrderDetailsBloc>().add(
                                FetchOrderDetails(widget.orderId, completer: detailsCompleter),
                              );
                              await Future.wait([settingsCompleter.future, detailsCompleter.future]);
                            },
                            child: SingleChildScrollView(
                              padding: EdgeInsets.symmetric(
                                horizontal: (isTablet() ? 24 : 8).w,
                                vertical: (isTablet() ? 16 : 18).h,
                              ),
                              child:
                                  Column(
                                    spacing: 12.h,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      // Order Status Banner
                                      // Removed OrderStatusBanner as it is now in the AppBar
                                      if (!_isOrderCancelled() && order.status?.toLowerCase() != 'delivered')
                                        ClipRRect(
                                          borderRadius: BorderRadius.circular(12.r),
                                          child: Container(
                                            height: 160.h,
                                            width: double.infinity,
                                            decoration: BoxDecoration(
                                              color: Theme.of(context).colorScheme.surfaceContainerHighest,
                                              borderRadius: BorderRadius.circular(12.r),
                                            ),
                                            child: Stack(
                                              children: [
                                                UnifiedMapWidget(
                                                  mode:
                                                      (order.status?.toLowerCase() == 'out_for_delivery' ||
                                                              order.status?.toLowerCase() == 'collected' ||
                                                              order.status?.toLowerCase() == 'delivered')
                                                          ? MapViewMode.customerDelivery
                                                          : MapViewMode.storePickup,
                                                  order: order,
                                                ),
                                                Positioned.fill(
                                                  child: Container(
                                                    decoration: BoxDecoration(
                                                      gradient: LinearGradient(
                                                        colors: [
                                                          Colors.black.withValues(alpha: 0.3),
                                                          Colors.transparent,
                                                        ],
                                                        begin: Alignment.topRight,
                                                        end: Alignment.bottomLeft,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                                Positioned(
                                                  top: 12.h,
                                                  right: 12.w,
                                                  child: GestureDetector(
                                                    onTap: () {
                                                      context.push(
                                                        AppRoutes.fullScreenMap,
                                                        extra: {'order': order, 'sourceTab': widget.sourceTab},
                                                      );
                                                    },
                                                    child: Container(
                                                      padding: EdgeInsets.all(8.r),
                                                      decoration: BoxDecoration(
                                                        color: Colors.white,
                                                        shape: BoxShape.circle,
                                                        boxShadow: [
                                                          BoxShadow(
                                                            color: Colors.black.withValues(alpha: 0.15),
                                                            blurRadius: 6,
                                                            offset: const Offset(0, 2),
                                                          ),
                                                        ],
                                                      ),
                                                      child: Icon(
                                                        Icons.fullscreen_rounded,
                                                        color: AppColors.primaryColor,
                                                        size: 24.sp,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),

                                      StatisticsRow(order: order),

                                      // Payment Method Card
                                      PaymentMethodCard(order: order),

                                      // Order Note Card
                                      if (order.orderNote != null && order.orderNote != "") OrderNoteCard(order: order),
                                      OrderItemsSection(
                                        order: order,
                                        isExpanded: _isItemsExpanded,
                                        onToggle: () {
                                          setState(() {
                                            _isItemsExpanded = !_isItemsExpanded;
                                          });
                                        },
                                        storeGroups: _buildStoreGroups(order),
                                        onCollectAll:
                                            (!widget.from &&
                                                    order.status?.toLowerCase() == 'assigned' &&
                                                    _hasUncollectedItems())
                                                ? _collectAllItems
                                                : null,
                                        collectingStoreIds: _collectingStoreIds,
                                        collectedItems: _collectedItems,
                                        onCollectAllForStore: _collectStoreItems,
                                      ),
                                      // Earnings Details Section
                                      EarningsDetailsSection(
                                        order: order,
                                        isExpanded: _isEarningsExpanded,
                                        onToggle: () {
                                          setState(() {
                                            _isEarningsExpanded = !_isEarningsExpanded;
                                          });
                                        },
                                      ),

                                      StoreDetailsSection(
                                        order: order,
                                        isExpanded: _isDeliveryExpanded,
                                        onToggle: () {
                                          setState(() {
                                            _isDeliveryExpanded = !_isDeliveryExpanded;
                                          });
                                        },
                                      ),

                                      // Shipping Details Section
                                      if (order.status?.toLowerCase() == 'assigned' ||
                                          order.status?.toLowerCase() == 'in_progress' ||
                                          order.status?.toLowerCase() == 'out_for_delivery' ||
                                          order.status?.toLowerCase() == 'on_the_way' ||
                                          order.status?.toLowerCase() == 'preparing' ||
                                          order.status?.toLowerCase() == 'ready' ||
                                          order.status?.toLowerCase() == 'ready_for_pickup') ...[
                                        ShippingDetailsSection(
                                          order: order,
                                          isExpanded: _isStoreDetailsExpanded,
                                          onToggle: () {
                                            setState(() {
                                              _isStoreDetailsExpanded = !_isStoreDetailsExpanded;
                                            });
                                          },
                                        ),
                                      ],
                                      CustomCard(
                                        padding: EdgeInsets.zero,
                                        child: InkWell(
                                          onTap: () => context.push(AppRoutes.support),
                                          borderRadius: BorderRadius.circular(12.r),
                                          child: Padding(
                                            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                              children: [
                                                Row(
                                                  children: [
                                                    Icon(
                                                      Icons.headset_mic_outlined,
                                                      color:
                                                          Theme.of(context).brightness == Brightness.dark
                                                              ? Colors.grey[400]
                                                              : Colors.grey[700],
                                                      size: sz(22, seprateTabletSize: 18).sp,
                                                    ),
                                                    SizedBox(width: 8.w),
                                                    CustomText(
                                                      text: AppLocalizations.of(context)!.support,
                                                      fontSize: sz(16, seprateTabletSize: 13),
                                                      fontWeight: FontWeight.w500,
                                                      color: const Color(0xFF6B6B6B),
                                                    ),
                                                  ],
                                                ),
                                                Icon(
                                                  Icons.arrow_forward_ios,
                                                  color: Colors.grey[400],
                                                  size: sz(16, seprateTabletSize: 12).sp,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      if (_canShowCancelDeliveryAction() && _hasCancellableItems()) ...[
                                        CustomButton(
                                          text: AppLocalizations.of(context)!.cancelDelivery,
                                          onPressed: _openCancelDeliverySheet,
                                          isLoading: _isCancellingDelivery,
                                          backgroundColor: AppColors.errorColor,
                                          textColor: Colors.white,
                                          width: double.infinity,
                                          padding: EdgeInsets.symmetric(
                                            horizontal: (isTablet() ? 18 : 24).w,
                                            vertical: (isTablet() ? 10 : 12).h,
                                          ),
                                          textStyle: TextStyle(
                                            fontSize: sz(16, seprateTabletSize: 12).sp,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                        SizedBox(height: 12.h),
                                      ],
                                      if (_canShowCancelOrderAction())
                                        CustomButton(
                                          text: AppLocalizations.of(context)!.cancelOrder,
                                          onPressed: _showCancelOrderDialog,
                                          isLoading: _isCancellingOrder,
                                          backgroundColor: AppColors.errorColor,
                                          textColor: Colors.white,
                                          width: double.infinity,
                                          padding: EdgeInsets.symmetric(
                                            horizontal: (isTablet() ? 18 : 24).w,
                                            vertical: (isTablet() ? 10 : 12).h,
                                          ),
                                          textStyle: TextStyle(
                                            fontSize: sz(16, seprateTabletSize: 12).sp,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      SizedBox(height: 60.h), // Bottom padding for swipe button
                                    ],
                                  ).fadeAndSlideAnimation(),
                            ),
                          ),
                          // Add confetti widget for celebration at the top center of the screen
                          Align(
                            alignment: Alignment.topCenter,
                            child: ConfettiWidget(
                              confettiController: _confettiController,
                              blastDirectionality: BlastDirectionality.explosive, // Explode from center
                              blastDirection: 1.57, // Shoot downwards (pi/2)
                              emissionFrequency: 0.05,
                              numberOfParticles: 20,
                              maxBlastForce: 5,
                              minBlastForce: 2,
                              gravity: 0.1,
                              colors: const [
                                Colors.green,
                                Colors.blue,
                                Colors.purple,
                                Colors.orange,
                                Colors.red,
                                Colors.yellow,
                                Colors.pink,
                                Colors.teal,
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                bottomNavigationBar: _buildBottomSheet(),
              );
            },
          );
        },
      ),
    );
  }

  void _showArrivalConfirmationDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: Row(
            children: [
              const Icon(Icons.location_on, color: Colors.green),
              SizedBox(width: 8.w),
              CustomText(text: AppLocalizations.of(context)!.confirmArrival, fontSize: 16, fontWeight: FontWeight.w600),
            ],
          ),
          content: CustomText(text: AppLocalizations.of(context)!.haveYouReachedAddress),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(dialogContext),
              child: CustomText(text: AppLocalizations.of(context)!.cancel),
            ),
            CustomButton(
              text: AppLocalizations.of(context)!.yesImHere,
              onPressed: () {
                Navigator.pop(dialogContext);

                // Mark ALL items as reached destination using the bloc
                if (_fetchedOrder?.items != null) {
                  for (final item in _fetchedOrder!.items!) {
                    if (item.id != null) {
                      context.read<OrderDetailsBloc>().add(MarkItemReachedDestination(_fetchedOrder!.id!, item.id!));
                    }
                  }
                }

                // Show success message
                ToastManager.show(
                  context: context,
                  message: AppLocalizations.of(context)!.arrivalConfirmedViewDetails,
                  type: ToastType.success,
                );
              },
              backgroundColor: AppColors.primaryColor,
              textColor: Colors.white,
            ),
          ],
        );
      },
    );
  }

  // Helper method to build the bottom sheet using the reusable widget
  Widget? _buildBottomSheet() {
    if (_fetchedOrder?.items == null) return null;

    final String? status = _fetchedOrder?.status?.toLowerCase();
    if (status == 'cancelled' || status == 'canceled') {
      return null;
    }

    List<Widget> actions = [];

    bool allItemsCollected = _fetchedOrder!.items!.every((item) {
      final s = item.status?.toLowerCase();
      return s == 'collected' || s == 'returning_to_store' || _collectedItems.contains(item.id.toString());
    });

    bool allItemsDelivered = _fetchedOrder!.items!.every((item) {
      return item.status?.toLowerCase() == 'delivered' || _deliveredItems.contains(item.id.toString());
    });

    final bool isOrderDelivered = _fetchedOrder?.status?.toLowerCase() == 'delivered';

    // 1. Show "Collect All Items" button if there are uncollected items (Removed - placed in StoreDetailsSection)
    // 2. Show "Deliver All" button if there are undelivered collected items (Only when all items are collected)
    if (!_hasUncollectedItems() && _hasUndeliveredCollectedItems()) {
      actions.add(
        ActionBottomSheet(
          buttonText: AppLocalizations.of(context)!.deliverAll,
          onPressed: _isCollectingAll ? () {} : _deliverAllItems,
          buttonColor: AppColors.primaryColor,
          textColor: Colors.white,
        ),
      );
    }
    // 3. Show "All Done" button if all items are delivered and it is a bottom sheet
    else if (isOrderDelivered || (allItemsCollected && allItemsDelivered)) {
      actions.add(
        ActionBottomSheet(
          buttonText: AppLocalizations.of(context)!.allDone,
          onPressed: _showEarningsPopup,
          buttonColor: AppColors.primaryColor,
          textColor: Colors.white,
        ),
      );
    }

    if (actions.isEmpty) return null;

    // ✅ Return multiple buttons UI wrapped in a styled container
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        boxShadow: [
          BoxShadow(color: AppColors.primaryColor.withValues(alpha: 0.3), blurRadius: 10, offset: const Offset(0, -4)),
        ],
      ),
      child: SafeArea(top: false, child: Column(mainAxisSize: MainAxisSize.min, children: actions)),
    );
  }

  bool _areAllItemsCollected() {
    return OrderService.areAllItemsCollected(_fetchedOrder);
  }

  bool _hasUncollectedItems() {
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return false;
    return items.any((item) {
      final s = item.status?.toLowerCase();
      return s != 'collected' && s != 'delivered' && s != 'returning_to_store';
    });
  }

  bool _areAllItemsStrictlyCollected() {
    return OrderService.areAllItemsStrictlyCollected(_fetchedOrder);
  }

  bool _canShowCancelOrderAction() {
    final status = _fetchedOrder?.status?.toLowerCase();
    if (status == null) return false;
    if (status == 'delivered' || status == 'cancelled' || status == 'canceled') {
      return false;
    }
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return false;
    final anyTouched = items.any((item) {
      final s = item.status?.toLowerCase();
      if (s == 'collected' || s == 'delivered' || s == 'returning_to_store') {
        return true;
      }
      return _collectedItems.contains(item.id.toString());
    });
    return !anyTouched;
  }

  bool _canShowCancelDeliveryAction() {
    return _fetchedOrder?.status?.toLowerCase() == 'out_for_delivery';
  }

  Future<String?> _submitCancelOrder(String reason) async {
    if (_fetchedOrder?.id == null || _isCancellingOrder) {
      return 'Unable to cancel order right now';
    }

    setState(() {
      _isCancellingOrder = true;
    });

    try {
      final response = await OrderActionsRepo().cancelOrder(orderId: _fetchedOrder!.id!, note: reason);

      final isSuccess = response['success'] == true;
      final message = response['message']?.toString() ?? 'Failed to cancel order';

      if (!mounted) return message;

      if (isSuccess) {
        ToastManager.show(context: context, message: message, type: ToastType.success);
        return null;
      }

      ToastManager.show(context: context, message: message, type: ToastType.success);
      return message;
    } catch (e) {
      final message = e.toString().replaceFirst('Exception: ', '');
      if (mounted) {
        ToastManager.show(context: context, message: message, type: ToastType.success);
      }
      return message;
    } finally {
      if (mounted) {
        setState(() {
          _isCancellingOrder = false;
        });
      }
    }
  }

  Future<String?> _submitCancelDeliveryForItems(List<int> itemIds, String reasonCode, String? note) async {
    if (itemIds.isEmpty) {
      return 'Select at least one item to cancel delivery';
    }
    if (_isCancellingDelivery) {
      return 'Cancellation already in progress';
    }

    setState(() {
      _isCancellingDelivery = true;
    });

    try {
      String? successMessage;

      for (final orderItemId in itemIds) {
        final response = await OrderActionsRepo().markDeliveryFailed(
          orderItemId: orderItemId,
          reasonCode: reasonCode,
          note: note,
        );

        final isSuccess = response['success'] == true;
        final message = response['message']?.toString() ?? 'Failed to cancel delivery';

        if (!isSuccess) {
          if (mounted) {
            ToastManager.show(context: context, message: message, type: ToastType.error);
          }
          return message;
        }

        successMessage = message;
      }

      if (mounted) {
        ToastManager.show(context: context, message: successMessage ?? 'Delivery cancelled successfully');
        _refreshOrderData();
      }

      return null;
    } catch (e) {
      final message = e.toString().replaceFirst('Exception: ', '');
      if (mounted) {
        ToastManager.show(context: context, message: message, type: ToastType.error);
      }
      return message;
    } finally {
      if (mounted) {
        setState(() {
          _isCancellingDelivery = false;
        });
      }
    }
  }

  Future<void> _showCancelOrderDialog() async {
    if (_isCancellingOrder) return;
    final result = await DialogService.showCancelOrderDialog(context: context, onSubmit: _submitCancelOrder);
    if (!mounted) return;
    if (result == true) {
      context.read<MyOrdersBloc>().add(AllMyOrdersList(forceRefresh: true));
      context.read<AvailableOrdersBloc>().add(AllAvailableOrdersList(forceRefresh: true));
      if (context.canPop()) {
        context.pop();
      }
    }
  }

  Future<void> _openCancelDeliverySheet() async {
    if (_isCancellingDelivery) return;
    final order = _fetchedOrder;
    if (order == null) return;
    final List<Items> eligibleItems = order.items?.where(_isItemCancellable).toList() ?? const <Items>[];
    if (eligibleItems.isEmpty) {
      ToastManager.show(context: context, message: 'No items eligible for delivery cancellation', type: ToastType.info);
      return;
    }
    await CancelDeliverySheet.show(context: context, items: eligibleItems, onSubmit: _submitCancelDeliveryForItems);
  }

  bool _isItemCancellable(Items item) {
    final status = item.status?.toLowerCase();
    return status != 'delivered' && status != 'returning_to_store';
  }

  bool _hasCancellableItems() {
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return false;
    return items.any(_isItemCancellable);
  }

  bool _isOrderCancelled() {
    final status = _fetchedOrder?.status?.toLowerCase();
    return status == 'cancelled' || status == 'canceled';
  }

  int _getTotalItems() {
    return OrderService.getTotalItems(_fetchedOrder);
  }

  bool _hasItemsRequiringOtp() {
    return OrderService.hasItemsRequiringOtp(_fetchedOrder);
  }

  bool _areAllOtpItemsVerified() {
    return OrderService.areAllOtpItemsVerified(_fetchedOrder);
  }

  bool _hasCodItems() {
    return OrderService.hasCodItems(_fetchedOrder);
  }

  void _showCodPopup() {
    DialogService.showCodPopup(context, _fetchedOrder);
    setState(() {
      _codPopupShown = true;
    });
  }

  void _showCongratulationsGif() {
    // Use the same earnings popup logic since it's similar
    _showEarningsPopup();
  }

  void _collectItem(Items item) {
    // Collect the item directly (no OTP required)
    if (item.id != null) {
      // Set the current processing item ID for tracking
      setState(() {
        _processingItemIds.add(item.id.toString());
      });

      // Dispatch the API call - UI updates will be handled in BlocConsumer
      context.read<ItemsCollectedBloc>().add(ItemsCollected(item.id.toString()));
    }
  }

  void _deliverItemWithoutOtp(Items item) async {
    if (item.id != null) {
      // Set the current processing item ID for tracking
      setState(() {
        _processingItemIds.add(item.id.toString());
      });

      // Remove the force refresh that was causing bottom sheet to disappear
      // _forceBottomSheetRefresh();

      // Dispatch the API call to mark item as delivered
      context.read<ItemsCollectedBloc>().add(ItemsDelivered(item.id.toString()));
    }
  }

  void _deliverItem(Items item) async {
    if (item.id != null) {
      // Show OTP dialog for delivery
      final String? otp = await _showDeliveryOtpDialog();

      if (otp != null && otp.isNotEmpty) {
        // Set the current processing item ID for tracking
        setState(() {
          _processingItemIds.add(item.id.toString());
        });

        // Dispatch the API call - UI updates will be handled in BlocConsumer
        context.read<ItemsCollectedBloc>().add(ItemsCollectedWithOtp(orderItemId: item.id.toString(), otp: otp));
      }
    }
  }

  Future<String?> _showDeliveryOtpDialog() async {
    return await DialogService.showDeliveryOtpDialog(context);
  }

  void _showCustomerOtpDialog() async {
    await DialogService.showCustomerOtpDialog(context, _fetchedOrder);
  }

  List<StoreGroup> _buildStoreGroups(Orders order) {
    if (order.items == null || order.items!.isEmpty) return [];

    final Map<int?, List<Items>> groupedItems = {};
    for (var item in order.items!) {
      groupedItems.putIfAbsent(item.storeId, () => []).add(item);
    }

    final List<StoreGroup> storeGroups = [];

    groupedItems.forEach((storeId, items) {
      final routeDetail = order.deliveryRoute?.routeDetails?.firstWhere(
        (detail) => detail.storeId == storeId,
        orElse: () => RouteDetails(storeId: storeId),
      );

      final String storeName = routeDetail?.storeName ?? items.first.store?.name ?? 'Unknown Store';
      final String? storeAddress = routeDetail?.address ?? routeDetail?.landmark;

      final List<Widget> cards = items.map((item) => _buildItemCard(item)).toList();

      storeGroups.add(StoreGroup(storeId: storeId, storeName: storeName, storeAddress: storeAddress, itemCards: cards));
    });

    // Sort storeGroups based on the order of storeIds in deliveryRoute.routeDetails
    final routeStoreIds =
        order.deliveryRoute?.routeDetails?.map((d) => d.storeId).where((id) => id != null).toList() ?? [];

    storeGroups.sort((a, b) {
      final indexA = routeStoreIds.indexOf(a.storeId);
      final indexB = routeStoreIds.indexOf(b.storeId);
      if (indexA == -1 && indexB == -1) return 0;
      if (indexA == -1) return 1;
      if (indexB == -1) return -1;
      return indexA.compareTo(indexB);
    });

    return storeGroups;
  }

  Widget _buildItemCard(Items item) {
    final storeCoords = _resolveStoreCoords(item);
    return ItemCardService.buildItemCard(
      context: context,
      item: item,
      from: widget.from,
      collectedItems: _collectedItems,
      deliveredItems: _deliveredItems,
      otpVerifiedItems: _otpVerifiedItems,
      currentProcessingItemId:
          _processingItemIds.contains(item.id.toString())
              ? item.id.toString()
              : (_isCollectingAll && (_collectingStoreIds.isEmpty || _collectingStoreIds.contains(item.storeId))
                  ? 'collecting_all'
                  : null),
      fetchedOrder: _fetchedOrder,
      onCollect: () => _collectItem(item),
      onDelivered: () => _deliverItemWithoutOtp(item),
      onReachedDestination: () => _markItemReachedDestination(item),
      onItemOtpTap: _showItemOtpDialog,
      onNavigateToStore:
          (item.status?.toLowerCase() == 'returning_to_store' && storeCoords != null)
              ? () => _openStoreInMaps(storeCoords.$1, storeCoords.$2)
              : null,
    );
  }

  (double, double)? _resolveStoreCoords(Items item) {
    final routeDetails = _fetchedOrder?.deliveryRoute?.routeDetails;
    if (routeDetails == null || routeDetails.isEmpty) return null;
    if (item.storeId == null) return null;
    for (final route in routeDetails) {
      if (route.storeId == item.storeId && route.latitude != null && route.longitude != null) {
        return (route.latitude!, route.longitude!);
      }
    }
    return null;
  }

  Future<void> _openStoreInMaps(double latitude, double longitude) async {
    final uri = Uri.parse('https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude&travelmode=driving');
    try {
      final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
      if (!launched && mounted) {
        ToastManager.show(context: context, message: 'Unable to open Google Maps', type: ToastType.error);
      }
    } catch (_) {
      if (mounted) {
        ToastManager.show(context: context, message: 'Unable to open Google Maps', type: ToastType.error);
      }
    }
  }

  void _showItemOtpDialog(Items item) async {
    bool requiresOtp = item.product?.requiresOtp == 1;

    if (!requiresOtp) {
      _deliverItemWithoutOtp(item);
      return;
    }

    // Show simplified OTP dialog
    final String? otp = await DialogService.showDeliveryOtpDialog(context);

    if (otp != null && otp.isNotEmpty) {
      setState(() {
        _processingItemIds.add(item.id.toString());
      });

      // Show COD popup if payment method is COD and popup hasn't been shown yet
      if (widget.from && _hasCodItems() && !_codPopupShown) {
        _showCodPopup();
      }

      context.read<ItemsCollectedBloc>().add(ItemsCollectedWithOtp(orderItemId: item.id.toString(), otp: otp));
    }
  }

  void _collectAllItems() async {
    setState(() {
      _isCollectingAll = true;
    });

    OrderService.collectAllItems(
      order: _fetchedOrder,
      collectedItems: _collectedItems,
      onItemCollected: (itemId) {
        context.read<ItemsCollectedBloc>().add(ItemsCollected(itemId));
      },
      onError: (errorMessage) {
        setState(() {
          _isCollectingAll = false;
        });
        ToastManager.show(context: context, message: errorMessage, type: ToastType.error);
      },
    );
  }

  void _collectStoreItems(int storeId) {
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return;

    setState(() {
      _isCollectingAll = true;
    });

    int itemsToCollectCount = 0;

    for (var item in items) {
      if (item.storeId == storeId && item.id != null) {
        bool isCollectedFromApi =
            item.status?.toLowerCase() == 'collected' || item.status?.toLowerCase() == 'delivered';

        if (!isCollectedFromApi && !_collectedItems.contains(item.id.toString())) {
          itemsToCollectCount++;
          setState(() {
            _processingItemIds.add(item.id.toString());
            _collectingStoreIds.add(storeId);
          });
          context.read<ItemsCollectedBloc>().add(ItemsCollected(item.id.toString()));
        }
      }
    }

    if (itemsToCollectCount == 0) {
      setState(() {
        _isCollectingAll = false;
      });
    }
  }

  bool _hasUndeliveredCollectedItems() {
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return false;
    return items.any((item) {
      final s = item.status?.toLowerCase();
      final isCollected = s == 'collected' || _collectedItems.contains(item.id.toString());
      final isDelivered = s == 'delivered' || _deliveredItems.contains(item.id.toString());
      return isCollected && !isDelivered;
    });
  }

  void _deliverAllItems() async {
    final items = _fetchedOrder?.items;
    if (items == null || items.isEmpty) return;

    // Check if any of the collected but undelivered items require OTP and are not verified yet
    final bool hasUnverifiedOtpItems = items.any((item) {
      final s = item.status?.toLowerCase();
      final isCollected = s == 'collected' || _collectedItems.contains(item.id.toString());
      final isDelivered = s == 'delivered' || _deliveredItems.contains(item.id.toString());
      final requiresOtp = item.product?.requiresOtp == 1;
      final isOtpVerified = item.otpVerified == 1 || _otpVerifiedItems.contains(item.id.toString());

      return isCollected && !isDelivered && requiresOtp && !isOtpVerified;
    });

    if (hasUnverifiedOtpItems) {
      ToastManager.show(
        context: context,
        message: AppLocalizations.of(context)!.someItemsRequireOtp,
        type: ToastType.error,
      );
      return;
    }

    setState(() {
      _isCollectingAll = true;
    });

    for (final item in items) {
      final s = item.status?.toLowerCase();
      final isCollected = s == 'collected' || _collectedItems.contains(item.id.toString());
      final isDelivered = s == 'delivered' || _deliveredItems.contains(item.id.toString());

      if (isCollected && !isDelivered && item.id != null) {
        context.read<ItemsCollectedBloc>().add(ItemsDelivered(item.id.toString()));
      }
    }

    Future.delayed(const Duration(milliseconds: 500), () {
      if (mounted) {
        setState(() {
          _isCollectingAll = false;
        });
      }
    });
  }

  void _showEarningsPopup() {
    // Show confetti only if it hasn't been shown for this order yet
    if (!_hasShownConfetti) {
      _hasShownConfetti = true;
      _confettiController.play();
    }

    final availableOrdersBloc = context.read<AvailableOrdersBloc>();
    final myOrdersBloc = context.read<MyOrdersBloc>();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.r)),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.check_circle, color: Colors.green, size: (isTablet() ? 48 : 64).r),
              SizedBox(height: 16.h),
              CustomText(
                text: AppLocalizations.of(dialogContext)!.orderCompleted,
                fontSize: sz(20, seprateTabletSize: 16),
                fontWeight: FontWeight.bold,
                color: Colors.green,
              ),
              SizedBox(height: 8.h),
              CustomText(
                text: AppLocalizations.of(dialogContext)!.allItemsDeliveredSuccessfully,
                textAlign: TextAlign.center,
                fontSize: sz(16, seprateTabletSize: 12),
                color: Colors.grey,
              ),
              SizedBox(height: 16.h),
              Container(
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  color: AppColors.primaryColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Column(
                  children: [
                    CustomText(
                      text: AppLocalizations.of(dialogContext)!.yourEarningsBreakdown,
                      fontWeight: FontWeight.bold,
                      fontSize: sz(16, seprateTabletSize: 12),
                    ),
                    SizedBox(height: 12.h),
                    // Breakdown details
                    if (_fetchedOrder?.earnings?.breakdown != null) ...[
                      _buildBreakdownRow(
                        AppLocalizations.of(dialogContext)!.baseFee,
                        _fetchedOrder?.earnings?.breakdown?.baseFee,
                      ),
                      _buildBreakdownRow(
                        AppLocalizations.of(dialogContext)!.storePickupFee,
                        _fetchedOrder?.earnings?.breakdown?.perStorePickupFee,
                      ),
                      _buildBreakdownRow(
                        AppLocalizations.of(dialogContext)!.distanceFee,
                        _fetchedOrder?.earnings?.breakdown?.distanceBasedFee,
                      ),
                      _buildBreakdownRow(
                        AppLocalizations.of(dialogContext)!.orderIncentive,
                        _fetchedOrder?.earnings?.breakdown?.perOrderIncentive,
                      ),
                      Divider(height: 16.h, thickness: 1),
                    ],
                    // Total
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        CustomText(
                          text: AppLocalizations.of(dialogContext)!.totalEarnings,
                          fontWeight: FontWeight.bold,
                          fontSize: sz(16, seprateTabletSize: 12),
                        ),
                        CustomText(
                          text: CurrencyFormatter.formatAmount(dialogContext, _fetchedOrder?.earnings?.total ?? 0),
                          fontSize: sz(20, seprateTabletSize: 16),
                          fontWeight: FontWeight.w600,
                          color: AppColors.primaryColor,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 24.h),
              Row(
                children: [
                  Expanded(
                    child: CustomButton(
                      text: AppLocalizations.of(dialogContext)!.ok,
                      onPressed: () {
                        dialogContext.pop();
                      },
                      backgroundColor: AppColors.primaryColor,
                      textColor: Colors.white,
                      borderRadius: 8.r,
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      textStyle: TextStyle(fontSize: sz(16, seprateTabletSize: 12).sp, fontWeight: FontWeight.w600),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: CustomButton(
                      text: AppLocalizations.of(dialogContext)!.goToHome,
                      onPressed: () async {
                        // Close the dialog first
                        Navigator.pop(dialogContext);

                        // Refresh the appropriate list in background if blocs are available
                        try {
                          int targetTab = _getTargetTabForNavigation();
                          if (targetTab == 0) {
                            availableOrdersBloc.add(AllAvailableOrdersList(forceRefresh: true));
                          } else if (targetTab == 1) {
                            myOrdersBloc.add(AllMyOrdersList(forceRefresh: true));
                          }
                        } catch (_) {}

                        // Pop back to the previous screen (caller screen) to preserve active tab and state
                        if (widget.isBottomSheet) {
                          // Pop the bottom sheet
                          Navigator.pop(context);
                          // Pop the MapDeliveryPage itself, returning true to trigger caller's then() refresh
                          Navigator.pop(context, true);
                        } else {
                          // Pop the OrderDetailsPage itself, returning true
                          Navigator.pop(context, true);
                        }
                      },
                      textColor: Colors.black87,
                      borderRadius: 8.r,
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      textStyle: TextStyle(fontSize: sz(16, seprateTabletSize: 12).sp, fontWeight: FontWeight.w600),
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildBreakdownRow(String label, double? amount) {
    return UIHelperService.buildBreakdownRow(context, label, amount);
  }

  String _getStatusText() {
    return OrderService.getStatusText(context, _fetchedOrder, widget.from);
  }

  int _getCollectedItemsCount() {
    return OrderService.getCollectedItemsCount(_fetchedOrder);
  }

  void _markItemReachedDestination(Items item) {
    if (item.id != null) {
      OrderService.markItemReachedDestination(
        orderId: widget.orderId,
        itemId: item.id!,
        onMarkItemReachedDestination: (orderId, itemId) {
          context.read<OrderDetailsBloc>().add(MarkItemReachedDestination(orderId, itemId));
        },
      );
    }
  }

  int _getTargetTabForNavigation() {
    return OrderService.getTargetTabForNavigation(widget.sourceTab, widget.from);
  }
}

Future<void> _makePhoneCall(String phoneNumber) async {
  await PhoneService.makePhoneCall(phoneNumber);
}
