// screens/feed_page/pickup_order_details/pickup_order_details_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:hyper_local/config/helper.dart';
import 'package:hyper_local/l10n/app_localizations.dart';
import 'package:hyper_local/screens/feed_page/bloc/return_order/pickup_order_details_bloc/pickup_order_details_bloc.dart';
import 'package:hyper_local/screens/feed_page/bloc/return_order/pickup_orders_list_bloc/pickup_order_list_bloc.dart';
import 'package:hyper_local/screens/feed_page/bloc/return_order/update_return_order_status_bloc/update_return_order_status_bloc.dart';
import 'package:hyper_local/screens/feed_page/model/return_orders_list_model.dart';
import 'package:hyper_local/utils/widgets/custom_text.dart';
import 'package:hyper_local/utils/widgets/custom_image_container.dart';
import 'package:hyper_local/utils/widgets/custom_button.dart';
import 'package:hyper_local/utils/currency_formatter.dart';

import '../../../../config/colors.dart';
import '../../../../utils/widgets/custom_scaffold.dart';
import '../../../../utils/widgets/custom_appbar_without_navbar.dart';
import '../../../../utils/widgets/loading_widget.dart';
import '../../../../utils/widgets/toast_message.dart';
import '../../../../utils/services/phone_service.dart';
import '../../../../router/app_routes.dart';
import '../../bloc/return_order/pickup_order_details_bloc/pickup_order_details_state.dart';
import '../../bloc/return_order/update_return_order_status_bloc/update_return_order_status_state.dart';
import 'package:flutter_tabler_icons/flutter_tabler_icons.dart';
import 'package:location/location.dart';
import '../map/widgets/unified_map_widget.dart';
import '../../../../utils/widgets/custom_card.dart';
import 'package:latlong2/latlong.dart';
import 'package:hyper_local/screens/feed_page/view/map/store_pickup_route/services/navigation_service.dart';
import 'package:hyper_local/config/app_images.dart';

class PickupOrderDetailsPage extends StatefulWidget {
  final String returnId;

  const PickupOrderDetailsPage({super.key, required this.returnId});

  @override
  State<PickupOrderDetailsPage> createState() => _PickupOrderDetailsPageState();
}

class _PickupOrderDetailsPageState extends State<PickupOrderDetailsPage> {
  @override
  void initState() {
    super.initState();
    context.read<PickupOrderDetailsBloc>().add(
      FetchPickupOrderDetails(widget.returnId),
    );
  }

  void _showStatusUpdateSheet(Pickups pickup) {
    final currentStatus = pickup.pickupStatus ?? 'pending';

    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder:
          (ctx) => BlocProvider.value(
            value: context.read<UpdateReturnOrderStatusBloc>(),
            child: Padding(
              padding: EdgeInsets.all(20.w),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CustomText(
                    text: AppLocalizations.of(context)!.updateStatus,
                    fontSize: sz(20),
                    fontWeight: FontWeight.bold,
                  ),
                  SizedBox(height: 24.h),
                  if (currentStatus != 'picked_up' &&
                      currentStatus != 'delivered_to_seller')
                    _buildStatusOption(
                      ctx,
                      AppLocalizations.of(context)!.pickup,
                      'picked_up',
                      Icons.local_shipping,
                      Colors.blue,
                    ),
                  if (currentStatus == 'picked_up')
                    _buildStatusOption(
                      ctx,
                      AppLocalizations.of(context)!.deliveredToSeller,
                      'delivered_to_seller',
                      Icons.check_circle,
                      Colors.green,
                    ),
                  SizedBox(height: 20.h),
                ],
              ),
            ),
          ),
    );
  }

  Widget _buildStatusOption(
    BuildContext context,
    String label,
    String status,
    IconData icon,
    Color color,
  ) {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton.icon(
        onPressed: () {
          Navigator.pop(context);
          context.read<UpdateReturnOrderStatusBloc>().add(
            UpdateReturnOrderStatus(returnId: widget.returnId, status: status),
          );
        },
        icon: Icon(icon, color: Colors.white),
        label: CustomText(
          text: label,
          color: Colors.white,
          fontWeight: FontWeight.w600,
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          padding: EdgeInsets.symmetric(vertical: 16.h),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<PickupOrderDetailsBloc, PickupOrderDetailsState>(
      builder: (context, blocState) {
        final pickup = blocState.pickups;
        final currentStatus = pickup?.pickupStatus?.toLowerCase() ?? 'pending';
        final isDelivered = currentStatus == 'delivered_to_seller';

        return CustomScaffold(
          appBar: CustomAppBar(
            titleWidget: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CustomText(
                  text: AppLocalizations.of(context)!.pickupDetails,
                  fontSize: sz(18, seprateTabletSize: 14),
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.onSurface,
                ),
                if (pickup != null &&
                    blocState.status != ApiStatus.loading) ...[
                  SizedBox(height: 2.h),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CustomText(
                        text:
                            '${AppLocalizations.of(context)!.orderId} #${pickup.orderId}',
                        fontSize: sz(13, seprateTabletSize: 11),
                        fontWeight: FontWeight.w600,
                        color: Theme.of(
                          context,
                        ).colorScheme.onSurface.withValues(alpha: 0.6),
                      ),
                      SizedBox(width: 6.w),
                      Icon(
                        (currentStatus == 'delivered_to_seller')
                            ? Icons.check_circle
                            : Icons.access_time,
                        color:
                            (currentStatus == 'delivered_to_seller')
                                ? Colors.green
                                : Colors.orange,
                        size: sz(14, seprateTabletSize: 12).sp,
                      ),
                      SizedBox(width: 4.w),
                      CustomText(
                        text: currentStatus.replaceAll('_', ' ').toUpperCase(),
                        fontSize: sz(13, seprateTabletSize: 11),
                        fontWeight: FontWeight.w600,
                        color:
                            (currentStatus == 'delivered_to_seller')
                                ? Colors.green
                                : Colors.orange,
                      ),
                    ],
                  ),
                ],
              ],
            ),
            additionalActions: [
              if (pickup != null && !isDelivered)
                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 double currentLat = currentLocationData.latitude!;
                    final double currentLng = currentLocationData.longitude!;
                    final LatLng currentLatLng = LatLng(currentLat, currentLng);

                    if (currentStatus == 'picked_up') {
                      final store = pickup.store;
                      if (store != null) {
                        final destination =
                            (store.latitude != null && store.longitude != null)
                                ? '${store.latitude},${store.longitude}'
                                : (store.address ?? '');
                        NavigationService.openGoogleMapsToShippingAddress(
                          currentLatLng,
                          destination,
                          '',
                        );
                      }
                    } else {
                      final order = pickup.order;
                      if (order != null) {
                        final bool hasCoords =
                            order.shippingLatitude != null &&
                            order.shippingLongitude != null;
                        final destination =
                            hasCoords
                                ? '${order.shippingLatitude},${order.shippingLongitude}'
                                : (order.shippingAddress1 ?? '');
                        NavigationService.openGoogleMapsToShippingAddress(
                          currentLatLng,
                          destination,
                          hasCoords ? '' : order.shippingAddress2,
                        );
                      }
                    }
                  },
                  child: const CustomImageContainer(
                    imagePath: AppImages.googleMap,
                    height: 50,
                    width: 50,
                  ),
                ),
              const SizedBox(width: 10),
            ],
          ),
          bottomNavigationBar: _buildBottomNavBar(pickup),
          body: BlocConsumer<PickupOrderDetailsBloc, PickupOrderDetailsState>(
            listener: (context, state) {
              if (state.status == ApiStatus.failed) {
                ToastManager.show(
                  context: context,
                  message: state.message,
                  type: ToastType.error,
                );
              }
            },
            builder: (context, state) {
              if (state.status == ApiStatus.loading) {
                return const Center(child: LoadingWidget());
              }

              if (state.pickups == null) {
                return Center(
                  child: CustomText(
                    text: AppLocalizations.of(context)!.noPickupDataFound,
                  ),
                );
              }

              if (state.status == ApiStatus.success) {
                final pickup = state.pickups!;
                final currentStatus = pickup.pickupStatus ?? 'pending';
                final isDelivered = currentStatus == 'delivered_to_seller';

                return SingleChildScrollView(
                  padding: EdgeInsets.all(8.w),
                  child: Column(
                    children: [
                      // Embedded Map Box
                      if (!isDelivered) ...[
                        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:
                                      (currentStatus == 'picked_up')
                                          ? MapViewMode.returnToStore
                                          : MapViewMode.pickupFromCustomer,
                                  pickup: pickup,
                                ),
                                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.pickupOrderMap,
                                        extra: {
                                          'pickup': pickup,
                                          'locationType':
                                              (currentStatus == 'picked_up')
                                                  ? 'seller'
                                                  : 'customer',
                                        },
                                      );
                                    },
                                    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,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 16.h),
                      ],

                      _buildPaymentOverviewCard(pickup),
                      SizedBox(height: 16.h),

                      _buildReturnItemsCard(pickup),
                      SizedBox(height: 16.h),

                      _buildEarningsCard(pickup),
                      SizedBox(height: 16.h),

                      _buildStoreDetailsCard(pickup),
                      SizedBox(height: 16.h),

                      _buildCustomerDetailsCard(pickup, !isDelivered),
                    ],
                  ),
                );
              }

              return Center(
                child: CustomText(
                  text: AppLocalizations.of(context)!.noDetailsFound,
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget? _buildBottomNavBar(Pickups? pickup) {
    if (pickup == null) return null;
    final currentStatus = pickup.pickupStatus?.toLowerCase() ?? 'pending';
    final isDelivered = currentStatus == 'delivered_to_seller';

    if (isDelivered) return null;

    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: Padding(
          padding: EdgeInsets.symmetric(horizontal: 18.w, vertical: 12.h),
          child: BlocConsumer<
            UpdateReturnOrderStatusBloc,
            UpdateReturnOrderStatusState
          >(
            listener: (context, statusState) {
              if (statusState.returnId == widget.returnId) {
                if (statusState.status == ApiStatus.success) {
                  ToastManager.show(
                    context: context,
                    message: statusState.message,
                    type: ToastType.success,
                  );
                  context.read<PickupOrderListBloc>().add(
                    FetchPickupOrders(forceRefresh: true),
                  );
                  context.read<PickupOrderDetailsBloc>().add(
                    FetchPickupOrderDetails(widget.returnId),
                  );
                } else if (statusState.status == ApiStatus.failed) {
                  ToastManager.show(
                    context: context,
                    message: statusState.message,
                    type: ToastType.error,
                  );
                }
              }
            },
            builder: (context, statusState) {
              final isUpdating =
                  statusState.status == ApiStatus.loading &&
                  statusState.returnId == widget.returnId;

              return SizedBox(
                width: double.infinity,
                child: CustomButton(
                  text: AppLocalizations.of(context)!.updateStatus,
                  onPressed:
                      isUpdating ? () {} : () => _showStatusUpdateSheet(pickup),
                  isLoading: isUpdating,
                  backgroundColor: AppColors.primaryColor,
                  textColor: Colors.white,
                  borderRadius: 5.r,
                  textStyle: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildPaymentOverviewCard(Pickups pickup) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return CustomCard(
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
            child: Row(
              children: [
                Icon(
                  TablerIcons.credit_card,
                  color: isDark ? Colors.grey[400] : Colors.grey[700],
                  size: sz(22, seprateTabletSize: 18).sp,
                ),
                SizedBox(width: 8.w),
                CustomText(
                  text: AppLocalizations.of(context)!.paymentOverview,
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF6B6B6B),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: isDark ? Colors.grey[800] : Colors.grey[200],
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CustomText(
                  text: AppLocalizations.of(context)!.refundAmt,
                  fontSize: sz(14, seprateTabletSize: 11),
                  color: isDark ? Colors.grey[400] : Colors.grey[600],
                ),
                CustomText(
                  text: CurrencyFormatter.formatAmount(
                    context,
                    pickup.refundAmount ?? '0',
                  ),
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.bold,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildReturnItemsCard(Pickups pickup) {
    final item = pickup.orderItem;
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return CustomCard(
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
            child: Row(
              children: [
                Icon(
                  TablerIcons.box,
                  color: isDark ? Colors.grey[400] : Colors.grey[700],
                  size: sz(22, seprateTabletSize: 18).sp,
                ),
                SizedBox(width: 8.w),
                CustomText(
                  text: AppLocalizations.of(context)!.orderItems,
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF6B6B6B),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: isDark ? Colors.grey[800] : Colors.grey[200],
          ),
          
          // Store Name / Header for the item
          if (pickup.store != null)
            Padding(
              padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 12.h),
              child: Row(
                children: [
                  Icon(
                    TablerIcons.building_store,
                    color: AppColors.primaryColor,
                    size: 16.sp,
                  ),
                  SizedBox(width: 6.w),
                  CustomText(
                    text: pickup.store!.name ?? 'Store',
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: AppColors.primaryColor,
                  ),
                ],
              ),
            ),

          if (item != null)
            Padding(
              padding: EdgeInsets.all(16.h),
              child: Row(
                children: [
                  CustomImageContainer(
                    width: 50.w,
                    height: 50.h,
                    imagePath: item.product?.image ?? '',
                    backgroundColor:
                        isDark ? Colors.grey[800] : const Color(0xFFF3F4F6),
                    borderRadius: BorderRadius.circular(8.r),
                    errorWidget: Center(
                      child: Icon(Icons.shopping_bag, size: sz(20).sp),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CustomText(
                          text:
                              item.product?.name ??
                              AppLocalizations.of(context)!.unknownProduct,
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                        SizedBox(height: 4.h),
                        CustomText(
                          text:
                              '${AppLocalizations.of(context)!.quantity} ${item.quantity ?? 1}',
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 12.w),
                  CustomText(
                    text: CurrencyFormatter.formatAmount(
                      context,
                      pickup.refundAmount ?? '0',
                    ),
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ],
              ),
            ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CustomText(
                  text:
                      '${AppLocalizations.of(context)!.total} (${AppLocalizations.of(context)!.oneItem})',
                  fontSize: 14,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
                CustomText(
                  text: CurrencyFormatter.formatAmount(
                    context,
                    pickup.refundAmount ?? '0',
                  ),
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEarningsCard(Pickups pickup) {
    final breakdown = pickup.earnings?.breakdown;
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return CustomCard(
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
            child: Row(
              children: [
                Icon(
                  TablerIcons.receipt,
                  color: isDark ? Colors.grey[400] : Colors.grey[700],
                  size: sz(22, seprateTabletSize: 18).sp,
                ),
                SizedBox(width: 8.w),
                CustomText(
                  text: AppLocalizations.of(context)!.earnings,
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF6B6B6B),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: isDark ? Colors.grey[800] : Colors.grey[200],
          ),
          Padding(
            padding: EdgeInsets.all(16.h),
            child: Column(
              children: [
                _buildRow(
                  '${AppLocalizations.of(context)!.baseFee} :',
                  CurrencyFormatter.formatAmount(
                    context,
                    breakdown?.baseFee ?? 0,
                  ),
                ),
                _buildRow(
                  '${AppLocalizations.of(context)!.perStorePickupFee} :',
                  CurrencyFormatter.formatAmount(
                    context,
                    breakdown?.perStorePickupFee ?? 0,
                  ),
                ),
                _buildRow(
                  '${AppLocalizations.of(context)!.distanceFee} :',
                  CurrencyFormatter.formatAmount(
                    context,
                    breakdown?.distanceBasedFee ?? 0,
                  ),
                ),
                _buildRow(
                  '${AppLocalizations.of(context)!.incentive} :',
                  CurrencyFormatter.formatAmount(
                    context,
                    breakdown?.perOrderIncentive ?? 0,
                  ),
                ),
                const Divider(height: 24, color: Color(0xFFEEEEEE)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CustomText(
                      text: AppLocalizations.of(context)!.totalEarnings,
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                    CustomText(
                      text: CurrencyFormatter.formatAmount(
                        context,
                        pickup.earnings?.total ?? 0,
                      ),
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStoreDetailsCard(Pickups pickup) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    // Extract stores from routeDetails, filtering out customer location
    final stores = pickup.deliveryRoute?.routeDetails
        ?.where((s) => s.storeName?.toLowerCase() != 'customer location' && s.storeId != null)
        .toList() ?? [];

    return CustomCard(
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
            child: Row(
              children: [
                Icon(
                  TablerIcons.building_store,
                  color: isDark ? Colors.grey[400] : Colors.grey[700],
                  size: sz(22, seprateTabletSize: 18).sp,
                ),
                SizedBox(width: 8.w),
                CustomText(
                  text: AppLocalizations.of(context)!.storeDetails,
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF6B6B6B),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: isDark ? Colors.grey[800] : Colors.grey[200],
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
            child: Column(
              children: [
                if (stores.isNotEmpty) ...[
                  for (int i = 0; i < stores.length; i++) ...[
                    if (i > 0)
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        child: Divider(height: 1, thickness: 1, color: isDark ? Colors.grey[800] : Colors.grey[200]),
                      ),
                    Row(
                      children: [
                        Container(
                          width: (isTablet() ? 40 : 48).w,
                          height: (isTablet() ? 40 : 48).h,
                          decoration: BoxDecoration(
                            color: isDark ? Colors.grey[800] : const Color(0xFFF3F4F6),
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Icon(
                              TablerIcons.building_store,
                              color: isDark ? Colors.grey[300] : Colors.grey[700],
                              size: sz(24, seprateTabletSize: 20).sp,
                            ),
                          ),
                        ),
                        SizedBox(width: 12.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              CustomText(
                                text: stores[i].storeName ?? 'Store',
                                fontSize: sz(16, seprateTabletSize: 13),
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                              if (stores[i].address != null && stores[i].address!.isNotEmpty) ...[
                                SizedBox(height: 4.h),
                                CustomText(
                                  text: stores[i].address!,
                                  fontSize: sz(13, seprateTabletSize: 10),
                                  color: isDark ? Colors.grey[400] : Colors.grey[500],
                                ),
                              ],
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ] else if (pickup.store != null) ...[
                  Row(
                    children: [
                      Container(
                        width: 48.w,
                        height: 48.h,
                        decoration: BoxDecoration(
                          color: isDark ? Colors.grey[800] : const Color(0xFFF3F4F6),
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: Icon(
                            TablerIcons.building_store,
                            color: isDark ? Colors.grey[300] : Colors.grey[700],
                            size: sz(24, seprateTabletSize: 20).sp,
                          ),
                        ),
                      ),
                      SizedBox(width: 12.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            CustomText(
                              text: pickup.store!.name ?? 'Store',
                              fontSize: sz(16, seprateTabletSize: 13),
                              fontWeight: FontWeight.bold,
                              color: Theme.of(context).colorScheme.onSurface,
                            ),
                            if (pickup.store!.address != null && pickup.store!.address!.isNotEmpty) ...[
                              SizedBox(height: 4.h),
                              CustomText(
                                text: pickup.store!.address!,
                                fontSize: sz(13, seprateTabletSize: 10),
                                color: isDark ? Colors.grey[400] : Colors.grey[500],
                              ),
                            ],
                          ],
                        ),
                      ),
                    ],
                  ),
                ] else
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    child: CustomText(
                      text: AppLocalizations.of(context)!.noData,
                      fontSize: sz(16, seprateTabletSize: 12),
                      color: Colors.grey,
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCustomerDetailsCard(Pickups pickup, bool isDelivered) {
    final order = pickup.order;
    final isDark = Theme.of(context).brightness == Brightness.dark;
    return CustomCard(
      padding: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
            child: Row(
              children: [
                Icon(
                  TablerIcons.map_pin,
                  color: isDark ? Colors.grey[400] : Colors.grey[700],
                  size: sz(22, seprateTabletSize: 18).sp,
                ),
                SizedBox(width: 8.w),
                CustomText(
                  text: AppLocalizations.of(context)!.shippingDetails,
                  fontSize: sz(16, seprateTabletSize: 13),
                  fontWeight: FontWeight.w500,
                  color: const Color(0xFF6B6B6B),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            thickness: 1,
            color: isDark ? Colors.grey[800] : Colors.grey[200],
          ),
          Padding(
            padding: EdgeInsets.all(16.h),
            child: Column(
              children: [
                _buildRow(
                  '${AppLocalizations.of(context)!.fullName} :',
                  order?.shippingName ?? 'N/A',
                ),
                if (isDelivered && order?.shippingPhone != null)
                  _buildRow(
                    '${AppLocalizations.of(context)!.phone} :',
                    order!.shippingPhone!,
                    trailing: GestureDetector(
                      onTap: () async {
                        try {
                          await PhoneService.makePhoneCall(order.shippingPhone!);
                        } catch (e) {
                          ToastManager.show(
                            context: context,
                            message: 'Could not launch phone dialer: $e',
                            type: ToastType.error,
                          );
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(6.w),
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor.withValues(alpha: 0.1),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.phone_in_talk_outlined,
                          color: Theme.of(context).primaryColor,
                          size: sz(18, seprateTabletSize: 14).sp,
                        ),
                      ),
                    ),
                  ),
                _buildRow(
                  '${AppLocalizations.of(context)!.address} :',
                  order?.shippingAddress1 ?? 'N/A',
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRow(String label, String value, {Widget? trailing}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6.h),
      child: Row(
        spacing: 5,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          CustomText(text: label, fontSize: 14, color: Colors.grey[600]),
          Expanded(
            child: CustomText(
              text: value,
              fontSize: 14,
              fontWeight: FontWeight.w500,
              textAlign: TextAlign.right,
            ),
          ),
          if (trailing != null) ...[
            SizedBox(width: 8.w),
            trailing,
          ],
        ],
      ),
    );
  }
}
