import 'dart:math';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_asset.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/enums/action_type.dart';
import 'package:niogu_ecommerce_v1/core/enums/approval_process.dart';
import 'package:niogu_ecommerce_v1/core/enums/delivery_fee_type.dart';
import 'package:niogu_ecommerce_v1/core/enums/delivery_type.dart';
import 'package:niogu_ecommerce_v1/core/enums/order_status.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/utils/currency_format.dart';
import 'package:niogu_ecommerce_v1/core/utils/extenstion_format.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/core/utils/time_zone.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.dart';
import 'package:niogu_ecommerce_v1/features/checkout/domain/entities/checkout.dart';
import 'package:niogu_ecommerce_v1/features/home/presentation/providers/home_provider.dart';
import 'package:niogu_ecommerce_v1/features/order/domain/entities/order.dart';
import 'package:niogu_ecommerce_v1/features/order/presentation/providers/order_provider.dart';
import 'package:sizer/sizer.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';

class OrderDetailScreen extends ConsumerStatefulWidget {
  final OrderInfo orderInfo;
  const OrderDetailScreen({super.key, required this.orderInfo});

  @override
  ConsumerState<OrderDetailScreen> createState() => _OrderDetailScreenState();
}

class _OrderDetailScreenState extends ConsumerState<OrderDetailScreen> {
  late final OrderInfo _orderInfo;

  final timeZone = TimeZone.getCurrentTimeZone();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _orderInfo = widget.orderInfo;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  double _calculateDistance(
    double lat1,
    double lon1,
    double lat2,
    double lon2,
  ) {
    final p = 0.017453292519943295;
    final c = cos;
    final a =
        0.5 -
        c((lat2 - lat1) * p) / 2 +
        c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
    return 12742 * asin(sqrt(a));
  }

  void _showPaymentProof() {
    showDialog(
      context: context,
      useRootNavigator: true,
      builder: (context) => Dialog(
        insetPadding: EdgeInsets.symmetric(horizontal: 2.w, vertical: 2.h),
        backgroundColor: Colors.transparent,
        child: GestureDetector(
          onTap: () => Navigator.pop(context),
          child: CachedNetworkImage(
            imageUrl: _orderInfo.paymentProofUrl ?? '',
            imageBuilder: (context, imageProvider) {
              return Container(
                width: MediaQuery.of(context).size.width,
                constraints: BoxConstraints(maxWidth: 85.w, maxHeight: 85.h),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: imageProvider,
                    fit: BoxFit.cover,
                  ),
                ),
              );
            },
            errorWidget: (context, url, error) {
              return Container(
                height: double.infinity,
                width: MediaQuery.of(context).size.width,
                color: Colors.white,
                constraints: BoxConstraints(maxWidth: 85.w, maxHeight: 85.h),
                child: Icon(
                  Icons.error_outline_outlined,
                  size: 10.w,
                  color: Colors.grey.shade500,
                ),
              );
            },
            errorListener: (value) =>
                CustomSnackbar.showError(context, "Ups, terjadi kesalahan"),
          ),
        ),
      ),
    );
  }

  void _showCancelConfirmation(bool canAutmaticCancelled) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4.5.w),
          ),
          elevation: 0,
          backgroundColor: Colors.transparent,
          constraints: BoxConstraints(maxHeight: 80.h, maxWidth: 80.w),
          child: _buildCancelModalContent(canAutmaticCancelled),
        );
      },
    );
  }

  Widget _buildCancelModalContent(bool canAutmaticCancelled) {
    final orderStatus = _orderInfo.orderStatus == OrderStatus.confirmed
        ? 'dikonfirmasi'
        : 'dikirim';

    return Container(
      padding: EdgeInsets.all(6.w),
      decoration: BoxDecoration(
        color: Colors.white,
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.circular(4.5.w),
        boxShadow: const [
          BoxShadow(
            color: Colors.black26,
            blurRadius: 10.0,
            offset: Offset(0.0, 10.0),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: EdgeInsets.all(4.w),
            decoration: BoxDecoration(
              color: Colors.red.shade50,
              shape: BoxShape.circle,
            ),
            child: Icon(Icons.error_outline, color: Colors.red, size: 15.w),
          ),
          SizedBox(height: 3.h),
          Text(
            canAutmaticCancelled ? "Batalkan Pesanan?" : "Ajukan Pembatalan?",
            style: TextStyle(
              fontSize: AppFontSize.medium.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 1.5.h),
          Text(
            canAutmaticCancelled
                ? "Apakah anda yakin ingin membatalkan pesanan ini? Tindakan ini tidak dapat dibatalkan."
                : "Pesanan anda sudah $orderStatus. Permintaan pembatalan memerlukan persetujuan dari admin.",
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              color: Colors.grey.shade700,
              height: 1.4,
            ),
          ),
          SizedBox(height: 4.h),

          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () => Navigator.pop(context),
                  style: OutlinedButton.styleFrom(
                    side: BorderSide(color: Colors.grey.shade300),
                    padding: EdgeInsets.symmetric(vertical: 1.5.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                  ),
                  child: Text(
                    "Kembali",
                    style: TextStyle(
                      color: Colors.black87,
                      fontSize: AppFontSize.small.sp,
                    ),
                  ),
                ),
              ),
              SizedBox(width: 3.w),

              Expanded(
                child: ElevatedButton(
                  onPressed: () async {
                    final orderId = _orderInfo.id;

                    final orderNumber = _orderInfo.orderNumber;
                    if (canAutmaticCancelled) {
                      try {
                        await ref
                            .read(orderControllerProvider.notifier)
                            .cancelOrder(orderId);
                      } on ServerException catch (e, st) {
                        LogMessage.log.e(
                          e.toString(),
                          error: e,
                          stackTrace: st,
                        );
                        CustomSnackbar.showError(context, e.toString());
                        return;
                      }

                      context.pushNamed(
                        AppRoute.customActionScreen,
                        extra: {
                          'order_number': orderNumber,
                          'type': ActionType.cancel,
                        },
                      );
                    } else {
                      try {
                        await ref
                            .read(orderControllerProvider.notifier)
                            .cancellationRequest(orderId);
                      } on ServerException catch (e, st) {
                        LogMessage.log.e(
                          e.toString(),
                          error: e,
                          stackTrace: st,
                        );
                        CustomSnackbar.showError(context, e.toString());
                        return;
                      }

                      context.pushNamed(
                        AppRoute.customActionScreen,
                        extra: {
                          'order_number': orderNumber,
                          'type': ActionType.requestCancel,
                        },
                      );
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColor.primaryColor,
                    elevation: 0,
                    padding: EdgeInsets.symmetric(vertical: 1.5.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                  ),
                  child: Text(
                    canAutmaticCancelled ? "Ya, Batalkan" : "Ajukan",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: AppFontSize.small.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        int preparationTimeMinutes = 0;

        final configurationState = ref.watch(configurationControllerProvider);

        configurationState.whenData((configure) {
          if (configure != null) {
            preparationTimeMinutes = configure.preparationTimeMinutes ?? 0;
          }
        });

        final orderControllerState = ref.watch(orderControllerProvider);

        final isLoading = orderControllerState.isLoading;

        final isCancellation = _orderInfo.isCancellation;

        final cancellationAccepted = _orderInfo.cancellationAccepted;

        final approvalProcess = _orderInfo.approvalProcess;

        bool isProcess = false;

        bool isAccepted = false;

        if (approvalProcess != null) {
          isProcess =
              (isCancellation ?? false) &&
              approvalProcess == ApprovalProcess.waiting;

          isAccepted =
              (isCancellation ?? false) &&
              (cancellationAccepted ?? false) &&
              approvalProcess == ApprovalProcess.done;
        }

        final outletAddress = _orderInfo.outletAddressSnapshot;

        final customerAddress = _orderInfo.customerAddressSnapshot;

        var distance = 0.0;

        var strDistance = '';

        final isDelivery = _orderInfo.deliveryType == DeliveryType.delivery;

        if (isDelivery && outletAddress != null && customerAddress != null) {
          distance = _calculateDistance(
            outletAddress.latitude,
            outletAddress.longitude,
            customerAddress.latitude,
            customerAddress.longitude,
          );

          strDistance = '${distance.toStringAsFixed(1)} Km';

          if (distance < 1)
            strDistance = '${(distance * 1000).toStringAsFixed(0)} meter';
        }

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF8F9FA),
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  color: AppColor.primaryColor,
                  size: 7.w,
                ),
                onPressed: () => context.canPop()
                    ? context.pop()
                    : context.goNamed(AppRoute.homeScreen),
              ),
              title: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _orderInfo.orderNumber.toUniqueNumberCleaner(),
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: AppFontSize.small.sp,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  SizedBox(height: 0.5.h),

                  Text(
                    "${DateFormat('dd MMMM yyyy HH:mm').format(_orderInfo.createdAt)} $timeZone",
                    style: TextStyle(
                      color: Colors.grey.shade700,
                      fontSize: (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                ],
              ),
              centerTitle: true,
            ),
            body: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildStatusHeader(preparationTimeMinutes),

                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 4.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (approvalProcess != null) ...[
                          SizedBox(height: 6.h),
                          _buildCancellationStatus(isProcess, isAccepted),
                        ],
                        SizedBox(
                          height: !(approvalProcess != null) ? 6.h : 3.h,
                        ),
                        _buildSectionTitle("Informasi Pengiriman"),
                        _buildDeliveryInfoCard(
                          outletAddress: outletAddress,
                          customerAddress: customerAddress,
                          isDelivery: isDelivery,
                          distance: distance,
                          strDistance: strDistance,
                        ),

                        SizedBox(height: 3.h),

                        _buildSectionTitle("Rincian Produk"),
                        _buildItemInfoCard(),

                        SizedBox(height: 3.h),

                        _buildSectionTitle("Informasi Pembayaran"),
                        _buildPaymentInfoCard(),

                        SizedBox(height: 3.h),

                        _buildOrderSummaryCard(strDistance),

                        SizedBox(height: 4.h),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            bottomNavigationBar:
                _orderInfo.orderStatus == OrderStatus.canceled ||
                    _orderInfo.orderStatus == OrderStatus.completed
                ? null
                : _buildBottomAction(isLoading),
          ),
        );
      },
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: EdgeInsets.only(bottom: 1.5.h),
      child: Text(
        title,
        style: TextStyle(
          fontSize: AppFontSize.small.sp,
          fontWeight: FontWeight.bold,
          color: Colors.black87,
        ),
      ),
    );
  }

  Widget _buildStatusHeader(int preparationTimeMinutes) {
    final orderStatus = _orderInfo.orderStatus;

    final status = switch (orderStatus) {
      OrderStatus.pending_payment => 'Diproses',
      OrderStatus.pending_confirmation => 'Diproses',
      OrderStatus.confirmed => 'Dikonfirmasi',
      OrderStatus.in_progress => 'Dikirim',
      OrderStatus.completed => 'Selesai',
      OrderStatus.canceled => 'Dibatalkan',
    };

    final animation = switch (orderStatus) {
      OrderStatus.pending_payment => AppAsset.PENDING_ORDER,
      OrderStatus.pending_confirmation => AppAsset.PENDING_ORDER,
      OrderStatus.confirmed => AppAsset.PENDING_ORDER,
      OrderStatus.in_progress => AppAsset.IN_PROGRESS_ORDER,
      OrderStatus.completed => AppAsset.COMPLETED_ORDER,
      OrderStatus.canceled => AppAsset.FAILED_ORDER,
    };

    return Stack(
      clipBehavior: Clip.none,
      alignment: Alignment.center,
      children: [
        Container(
          width: double.infinity,
          height: 25.h,
          color: orderStatus == OrderStatus.in_progress
              ? Colors.white
              : AppColor.primaryColor.withOpacity(0.05),
          child: Center(child: Image.asset(animation)),
        ),
        Positioned(
          bottom: -4.h,
          child: Container(
            width: 85.w,
            padding: EdgeInsets.all(4.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(2.5.w),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Column(
              children: [
                Text(
                  orderStatus == OrderStatus.completed ||
                          orderStatus == OrderStatus.canceled
                      ? "Pesanan $status"
                      : "Pesananmu Telah $status",
                  style: TextStyle(
                    color: AppColor.primaryColor,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.small.sp,
                  ),
                ),

                if ((_orderInfo.deliveryType == DeliveryType.delivery) &&
                        orderStatus == OrderStatus.pending_payment ||
                    orderStatus == OrderStatus.pending_confirmation ||
                    orderStatus == OrderStatus.confirmed) ...[
                  SizedBox(height: 1.h),
                  Text(
                    _orderInfo.deliveryPreference == "Hari ini (Segera)"
                        ? "Pesananmu segera dikirim"
                        : "Pesananmu dikirim pada ${_orderInfo.deliveryPreference}",
                    style: TextStyle(
                      color: Colors.black87,
                      fontSize: (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                ] else if (orderStatus == OrderStatus.pending_payment ||
                    orderStatus == OrderStatus.pending_confirmation) ...[
                  SizedBox(height: 1.h),
                  Text(
                    _orderInfo.deliveryPreference == "Hari ini (Segera)"
                        ? "Dapat di ambil dalam $preparationTimeMinutes menit lagi"
                        : "Dapat di ambil ${_orderInfo.deliveryPreference}",
                    style: TextStyle(
                      color: Colors.black87,
                      fontSize: (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildCancellationStatus(bool isProcess, bool isAccepted) {
    Color primaryColor;

    IconData statusIcon;

    String title;

    if (isProcess) {
      primaryColor = AppColor.primaryColor;
      statusIcon = Icons.hourglass_empty;
      title = "Permintaan pembatalan sedang diproses";
    } else if (isAccepted) {
      primaryColor = Colors.red;
      statusIcon = Icons.cancel_outlined;
      title = "Permintaan pembatalan diterima";
    } else {
      primaryColor = Colors.orange;
      statusIcon = Icons.error_outline;
      title = "Permintaan pembatalan ditolak";
    }

    return Container(
      margin: EdgeInsets.only(top: 2.h),
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: primaryColor.withOpacity(0.05),
        borderRadius: BorderRadius.circular(2.5.w),
        border: Border.all(color: primaryColor.withOpacity(0.2)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(statusIcon, color: primaryColor, size: 5.w),
          SizedBox(width: 3.w),

          Text(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: AppFontSize.small.sp,
              color: primaryColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeliveryInfoCard({
    required OutletAddressSnapshot? outletAddress,
    required CustomerAddressSnapshot? customerAddress,
    required bool isDelivery,
    required double distance,
    required String strDistance,
  }) {
    return _buildWhiteCard(
      child: Column(
        children: [
          _buildLocationRow(
            icon: Icons.location_on_outlined,
            color: Colors.red,
            label: isDelivery ? "Dari" : "Tempat Pengambilan",
            place: _orderInfo.outletNameSnapshot,
            address: outletAddress?.fullAddress,
          ),

          if (distance > 0)
            Padding(
              padding: EdgeInsets.only(left: 2.5.w),
              child: Row(
                children: [
                  Container(width: 1, height: 6.h, color: Colors.grey.shade300),
                  SizedBox(width: 4.w),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 2.w,
                      vertical: 0.5.h,
                    ),
                    decoration: BoxDecoration(
                      color: AppColor.primaryColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(1.w),
                    ),
                    child: Text(
                      "Jarak : $strDistance",
                      style: TextStyle(
                        fontSize: (AppFontSize.small - 1.25).sp,
                        fontWeight: FontWeight.bold,
                        color: AppColor.primaryColor,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          if (isDelivery) ...[
            SizedBox(height: 3.h),

            _buildLocationRow(
              icon: Icons.location_on,
              color: Colors.green,
              label: "Tujuan",
              place: customerAddress!.label,
              address: customerAddress.fullAddress,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildLocationRow({
    required IconData icon,
    required Color color,
    required String label,
    required String place,
    String? address,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(icon, color: color, size: 5.w),
        SizedBox(width: 3.w),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: TextStyle(
                  color: Colors.grey.shade700,
                  fontSize: (AppFontSize.small - 1.25).sp,
                ),
              ),
              SizedBox(height: 0.5.h),
              Text(
                place,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: (AppFontSize.small - 1.25).sp,
                ),
              ),
              if (address != null) ...[
                SizedBox(height: 0.5.h),
                Text(
                  address,
                  style: TextStyle(
                    color: Colors.black87,
                    fontSize: (AppFontSize.small - 1.25).sp,
                  ),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildItemInfoCard() {
    return _buildWhiteCard(
      child: ListView.separated(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _orderInfo.orderItems.length,
        separatorBuilder: (context, index) =>
            Divider(height: 3.h, color: Colors.grey.shade100),
        itemBuilder: (context, index) {
          final item = _orderInfo.orderItems[index];
          return Row(
            children: [
              CachedNetworkImage(
                imageUrl: item.productImageUrlSnapshot ?? 'error',
                imageBuilder: (context, imageProvider) {
                  return Container(
                    width: 15.w,
                    height: 15.w,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(2.w),
                      image: DecorationImage(
                        image: imageProvider,
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                },
                errorWidget: (context, url, error) {
                  return Container(
                    width: 15.w,
                    height: 15.w,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(2.w),
                    ),
                    child: Icon(Icons.image, color: Colors.grey.shade300),
                  );
                },
              ),
              SizedBox(width: 4.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.productNameSnapshot,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: (AppFontSize.small - 1.25).sp,
                      ),
                    ),

                    if (item.productVariantNameSnapshot != null &&
                        item.productVariantNameSnapshot!.isNotEmpty) ...[
                      SizedBox(height: 0.75.h),

                      Text(
                        item.productVariantNameSnapshot!,
                        style: TextStyle(
                          color: Colors.grey.shade700,
                          fontSize: (AppFontSize.small - 1.25).sp,
                        ),
                      ),
                    ],

                    SizedBox(height: 0.75.h),

                    Text(
                      CurrencyFormat.formatToIdr(item.sellingPriceSnapshot, 0),
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: (AppFontSize.small - 1.25).sp,
                      ),
                    ),
                  ],
                ),
              ),
              Text(
                "x ${item.quantity}",
                style: TextStyle(
                  color: Colors.grey.shade700,
                  fontSize: (AppFontSize.small - 1.25).sp,
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildPaymentInfoCard() {
    final isPayOnTheSpot =
        (_orderInfo.deliveryType == DeliveryType.delivery &&
            _orderInfo.paymentMethod == 'COD') ||
        (_orderInfo.deliveryType == DeliveryType.pick_up &&
            _orderInfo.paymentMethod == 'Bayar Ditoko');
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: isPayOnTheSpot ? null : _showPaymentProof,
        child: _buildWhiteCard(
          child: Row(
            children: [
              Container(
                padding: EdgeInsets.all(2.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 5,
                    ),
                  ],
                ),
                child: Icon(
                  Icons.receipt_long_outlined,
                  color: AppColor.primaryColor,
                  size: 5.w,
                ),
              ),
              SizedBox(width: 3.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _orderInfo.paymentMethod,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: (AppFontSize.small - 1.25).sp,
                      ),
                    ),
                    if (!isPayOnTheSpot)
                      Text(
                        "Ketuk untuk lihat bukti pembayaran",
                        style: TextStyle(
                          fontSize: (AppFontSize.small - 1.25).sp,
                          color: Colors.grey.shade600,
                        ),
                      ),
                  ],
                ),
              ),
              if (!isPayOnTheSpot)
                Icon(
                  Icons.arrow_forward_ios,
                  size: 3.5.w,
                  color: Colors.grey.shade400,
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildOrderSummaryCard(String distance) {
    return _buildWhiteCard(
      child: Column(
        children: [
          _buildSummaryRow(
            "Subtotal Pesanan",
            CurrencyFormat.formatToIdr(_orderInfo.totalOrder, 0),
          ),
          if (_orderInfo.deliveryType == DeliveryType.delivery) ...[
            if (_orderInfo.deliveryFeeType == DeliveryFeeType.per_km) ...[
              _buildSummaryRow(
                "Biaya Pengiriman Per Km",
                CurrencyFormat.formatToIdr(_orderInfo.deliveryFee, 0),
              ),

              _buildSummaryRow(
                "Jarak Alamatmu Dengan Toko",
                "\u00B1 $distance",
              ),
            ],
            _buildSummaryRow(
              "Subtotal Pengiriman",
              CurrencyFormat.formatToIdr(_orderInfo.totalDeliveryFee, 0),
            ),
          ],
          const Divider(),
          _buildSummaryRow(
            "Total Pembayaran",
            CurrencyFormat.formatToIdr(_orderInfo.totalAmount, 0),
            isTotal: true,
          ),
        ],
      ),
    );
  }

  Widget _buildSummaryRow(String label, String value, {bool isTotal = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 0.8.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
              color: isTotal ? Colors.black : Colors.grey.shade700,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: (AppFontSize.small - 1.25).sp,
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
              color: isTotal ? AppColor.primaryColor : Colors.black,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWhiteCard({required Widget child}) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(2.5.w),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.02),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: child,
    );
  }

  Widget _buildBottomAction(bool isLoading) {
    final canCanceled =
        _orderInfo.orderStatus != OrderStatus.completed ||
        _orderInfo.orderStatus != OrderStatus.canceled;

    final canAutomaticCanceled =
        _orderInfo.orderStatus == OrderStatus.pending_payment ||
        _orderInfo.orderStatus == OrderStatus.pending_confirmation;

    final approvalProcess = _orderInfo.approvalProcess;

    return Container(
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, -5),
          ),
        ],
      ),
      child: ElevatedButton(
        onPressed: !canCanceled || (approvalProcess != null) || isLoading
            ? null
            : () => _showCancelConfirmation(canAutomaticCanceled),
        style: ElevatedButton.styleFrom(
          backgroundColor: AppColor.primaryColor,
          elevation: 0,
          minimumSize: Size(double.infinity, 6.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(2.5.w),
          ),
          disabledBackgroundColor: Colors.grey.shade300,
        ),
        child: Text(
          canAutomaticCanceled ? "Batalkan Pesanan" : "Ajukan Pembatalan",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            fontSize: AppFontSize.medium.sp,
          ),
        ),
      ),
    );
  }
}
