import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'dart:math' show cos, sin;

import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../../domain/order/order.dart';
import '../../../components/appbar/appbar.dart';

@RoutePage()
class OrderDetailPage extends StatelessWidget {
  final Order order;

  const OrderDetailPage({super.key, required this.order});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 120,
            pinned: true,
            backgroundColor: AppColor.primary,
            flexibleSpace: CustomAppBar(title: context.lang.order_details),
            elevation: 0,
          ),
          SliverToBoxAdapter(
            child: Column(
              children: [
                // Order Status Card
                _buildOrderStatusCard(context),
                const SizedBox(height: 16),

                // Table Visual Card (for dine-in)
                if (_isDineIn()) _buildTableVisualCard(context),

                // Order Info Card
                _buildOrderInfoCard(context),
                const SizedBox(height: 16),

                // Order Items Section
                _buildOrderItemsSection(context),
                const SizedBox(height: 16),

                // Payment Summary Card
                _buildPaymentSummaryCard(context),
                const SizedBox(height: 16),

                // Payment Methods Section
                _buildPaymentMethodsSection(context),
                const SizedBox(height: 24),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderStatusCard(BuildContext context) {
    Color statusColor = _getStatusColor(order.status);
    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            statusColor.withOpacity(0.15),
            statusColor.withOpacity(0.08),
            Colors.white,
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: const [0.0, 0.5, 1.0],
        ),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: statusColor.withOpacity(0.3), width: 1.5),
        boxShadow: [
          BoxShadow(
            color: statusColor.withOpacity(0.2),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
          BoxShadow(
            color: Colors.white,
            blurRadius: 8,
            offset: const Offset(-2, -2),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [statusColor, statusColor.withOpacity(0.8)],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: statusColor.withOpacity(0.4),
                        blurRadius: 8,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                  child: Icon(
                    _getStatusIcon(order.status),
                    color: Colors.white,
                    size: 28,
                  ),
                ),
                const SizedBox(width: 20),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        context.lang.order_number,
                        style: AppStyle.sm.copyWith(
                          color: AppColor.textSecondary,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        order.orderNumber,
                        style: AppStyle.xl.copyWith(
                          fontWeight: FontWeight.bold,
                          color: AppColor.textPrimary,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.7),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: statusColor.withOpacity(0.2)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        context.lang.order_status,
                        style: AppStyle.sm.copyWith(
                          color: AppColor.textSecondary,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 8,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [statusColor, statusColor.withOpacity(0.8)],
                          ),
                          borderRadius: BorderRadius.circular(25),
                          boxShadow: [
                            BoxShadow(
                              color: statusColor.withOpacity(0.3),
                              blurRadius: 6,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Text(
                          order.status.toUpperCase(),
                          style: AppStyle.sm.copyWith(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            letterSpacing: 0.5,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        context.lang.total_amount,
                        style: AppStyle.sm.copyWith(
                          color: AppColor.textSecondary,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Rp ${_formatCurrency(order.totalAmount)}',
                        style: AppStyle.xxl.copyWith(
                          fontWeight: FontWeight.bold,
                          color: AppColor.primary,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTableVisualCard(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      height: 220, // Increased height
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColor.primary,
            AppColor.primaryLight,
            AppColor.primary.withOpacity(0.8),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: const [0.0, 0.5, 1.0],
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: AppColor.primary.withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: ClipRRect(
        // Prevent overflow
        borderRadius: BorderRadius.circular(20),
        child: Stack(
          children: [
            // Background Pattern
            Positioned.fill(child: CustomPaint(painter: TablePatternPainter())),

            // Content with proper spacing
            Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  // Header
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: AppColor.white.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(15),
                          border: Border.all(
                            color: AppColor.white.withOpacity(0.3),
                            width: 1,
                          ),
                        ),
                        child: const Icon(
                          Icons.restaurant,
                          color: AppColor.white,
                          size: 24,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              context.lang.dine_in,
                              style: AppStyle.sm.copyWith(
                                color: AppColor.white.withOpacity(0.9),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            Text(
                              context.lang.dine_in_experience,
                              style: AppStyle.lg.copyWith(
                                color: AppColor.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 20), // Fixed spacing
                  // Table Number Visual
                  Expanded(
                    child: Center(
                      child: Container(
                        width: 90,
                        height: 90,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: RadialGradient(
                            colors: [
                              AppColor.white,
                              AppColor.white.withOpacity(0.9),
                              AppColor.white.withOpacity(0.7),
                            ],
                            stops: const [0.0, 0.7, 1.0],
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: AppColor.black.withOpacity(0.2),
                              blurRadius: 15,
                              offset: const Offset(0, 5),
                            ),
                          ],
                        ),
                        child: Stack(
                          children: [
                            // Table surface
                            Center(
                              child: Container(
                                width: 70,
                                height: 70,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: AppColor.white,
                                  border: Border.all(
                                    color: AppColor.primary.withOpacity(0.3),
                                    width: 2,
                                  ),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      context.lang.table,
                                      style: AppStyle.xs.copyWith(
                                        color: AppColor.primary.withOpacity(
                                          0.7,
                                        ),
                                        fontWeight: FontWeight.w600,
                                        letterSpacing: 1,
                                      ),
                                    ),
                                    Text(
                                      order.tableNumber,
                                      style: AppStyle.xl.copyWith(
                                        color: AppColor.primary,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            // Table legs (decorative)
                            ...List.generate(4, (index) {
                              final angle = (index * 90.0) * (3.14159 / 180);
                              return Positioned(
                                left: 45 + 30 * cos(angle) - 2,
                                top: 45 + 30 * sin(angle) - 8,
                                child: Container(
                                  width: 4,
                                  height: 16,
                                  decoration: BoxDecoration(
                                    color: AppColor.primary.withOpacity(0.3),
                                    borderRadius: BorderRadius.circular(2),
                                  ),
                                ),
                              );
                            }),
                          ],
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(height: 16), // Fixed spacing
                  // Bottom Info with flexible layout
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 6,
                          ),
                          decoration: BoxDecoration(
                            color: AppColor.white.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: AppColor.white.withOpacity(0.3),
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.people,
                                size: 16,
                                color: AppColor.white.withOpacity(0.9),
                              ),
                              const SizedBox(width: 6),
                              Text(
                                '${order.orderItems.length} ${context.lang.items}',
                                style: AppStyle.sm.copyWith(
                                  color: AppColor.white,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 12),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 6,
                          ),
                          decoration: BoxDecoration(
                            color: AppColor.success.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: AppColor.success.withOpacity(0.3),
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.schedule,
                                size: 16,
                                color: AppColor.white.withOpacity(0.9),
                              ),
                              const SizedBox(width: 6),
                              Text(
                                _formatDateTime(order.createdAt),
                                style: AppStyle.sm.copyWith(
                                  color: AppColor.white,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOrderInfoCard(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Colors.white, Color(0xFFFAFBFF)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: AppColor.primary.withOpacity(0.1)),
        boxShadow: [
          BoxShadow(
            color: AppColor.primary.withOpacity(0.08),
            blurRadius: 20,
            offset: const Offset(0, 5),
          ),
          const BoxShadow(
            color: Colors.white,
            blurRadius: 6,
            offset: Offset(-3, -3),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: AppColor.primaryGradient,
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Icon(
                    Icons.info_outline,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 16),
                Text(
                  context.lang.order_information,
                  style: AppStyle.xl.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.primary,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            if (_shouldShowTableNumber())
              _buildInfoRow(
                Icons.table_restaurant,
                context.lang.table,
                order.tableNumber,
              ),
            _buildInfoRow(
              Icons.delivery_dining,
              context.lang.order_type,
              order.orderType,
            ),
            _buildInfoRow(
              Icons.payment,
              context.lang.payment_status,
              order.paymentStatus,
            ),
            _buildInfoRow(
              Icons.access_time,
              context.lang.created,
              _formatDateTime(order.createdAt),
            ),
            if (order.notes.isNotEmpty)
              _buildInfoRow(Icons.note, context.lang.note, order.notes),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: AppColor.primary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(icon, size: 16, color: AppColor.primary),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: AppStyle.sm.copyWith(color: AppColor.textSecondary),
                ),
                const SizedBox(height: 2),
                Text(
                  value,
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.w600,
                    color: AppColor.textPrimary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOrderItemsSection(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: AppColor.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
            child: Row(
              children: [
                Text(
                  context.lang.order_item,
                  style: AppStyle.lg.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.textPrimary,
                  ),
                ),
                const Spacer(),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: AppColor.primary.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    '${order.orderItems.length} ${context.lang.item}',
                    style: AppStyle.sm.copyWith(
                      color: AppColor.primary,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
          ),
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.all(20),
            itemCount: order.orderItems.length,
            separatorBuilder: (context, index) => const Divider(height: 24),
            itemBuilder: (context, index) {
              final item = order.orderItems[index];
              return _buildOrderItemCard(context, item);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildOrderItemCard(BuildContext context, OrderItem item) {
    // Assume we add status to OrderItem model or determine from order status
    String itemStatus = _getItemStatus(context, item);
    Color itemStatusColor = _getItemStatusColor(itemStatus);

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            itemStatusColor.withOpacity(0.05),
            itemStatusColor.withOpacity(0.02),
            Colors.white,
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: itemStatusColor.withOpacity(0.3)),
        boxShadow: [
          BoxShadow(
            color: itemStatusColor.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [itemStatusColor, itemStatusColor.withOpacity(0.8)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: itemStatusColor.withOpacity(0.3),
                      blurRadius: 6,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.fastfood,
                  color: Colors.white,
                  size: 28,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            item.productName,
                            style: AppStyle.md.copyWith(
                              fontWeight: FontWeight.bold,
                              color: AppColor.textPrimary,
                            ),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: itemStatusColor.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            itemStatus,
                            style: AppStyle.xs.copyWith(
                              color: itemStatusColor,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: AppColor.primary.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            'Qty: ${item.quantity}',
                            style: AppStyle.xs.copyWith(
                              color: AppColor.primary,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Rp ${_formatCurrency(item.price)} each',
                          style: AppStyle.sm.copyWith(
                            color: AppColor.textSecondary,
                          ),
                        ),
                      ],
                    ),
                    if (item.discountAmount > 0) ...[
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: AppColor.error.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Text(
                          '${context.lang.discount}: -Rp ${_formatCurrency(item.discountAmount)}',
                          style: AppStyle.xs.copyWith(
                            color: AppColor.error,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.7),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: itemStatusColor.withOpacity(0.2)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  context.lang.total_item,
                  style: AppStyle.sm.copyWith(
                    color: AppColor.textSecondary,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      'Rp ${_formatCurrency(item.total)}',
                      style: AppStyle.lg.copyWith(
                        fontWeight: FontWeight.bold,
                        color: AppColor.primary,
                      ),
                    ),
                    if (item.discountAmount > 0)
                      Text(
                        'Rp ${_formatCurrency(item.subtotal)}',
                        style: AppStyle.xs.copyWith(
                          color: AppColor.textSecondary,
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentSummaryCard(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColor.primary.withOpacity(0.05),
            AppColor.primary.withOpacity(0.02),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColor.primary.withOpacity(0.2)),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              context.lang.payment_summary,
              style: AppStyle.lg.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColor.primary,
              ),
            ),
            const SizedBox(height: 16),
            _buildSummaryRow(context.lang.subtotal, order.subtotal),
            if (order.discountAmount > 0)
              _buildSummaryRow(
                context.lang.discount,
                -order.discountAmount,
                isDiscount: true,
              ),
            _buildSummaryRow(context.lang.tax, order.taxAmount),
            const Divider(height: 24),
            _buildSummaryRow(
              context.lang.total,
              order.totalAmount,
              isTotal: true,
            ),
            _buildSummaryRow(
              context.lang.paid,
              order.totalPaid,
              isSuccess: true,
            ),
            if (order.remainingAmount > 0)
              _buildSummaryRow(
                context.lang.remaining,
                order.remainingAmount,
                isError: true,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSummaryRow(
    String label,
    int amount, {
    bool isTotal = false,
    bool isDiscount = false,
    bool isSuccess = false,
    bool isError = false,
  }) {
    Color textColor = AppColor.textPrimary;
    if (isTotal) textColor = AppColor.primary;
    if (isDiscount) textColor = AppColor.error;
    if (isSuccess) textColor = AppColor.success;
    if (isError) textColor = AppColor.error;

    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: AppStyle.md.copyWith(
              color: isTotal ? AppColor.primary : AppColor.textSecondary,
              fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
            ),
          ),
          Text(
            '${amount < 0 ? '-' : ''}Rp ${_formatCurrency(amount.abs())}',
            style: AppStyle.md.copyWith(
              color: textColor,
              fontWeight: isTotal ? FontWeight.bold : FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentMethodsSection(BuildContext context) {
    if (order.payments.isEmpty) return const SizedBox();

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: AppColor.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
            child: Text(
              context.lang.payment_method,
              style: AppStyle.lg.copyWith(
                fontWeight: FontWeight.bold,
                color: AppColor.textPrimary,
              ),
            ),
          ),
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.all(20),
            itemCount: order.payments.length,
            separatorBuilder: (context, index) => const SizedBox(height: 12),
            itemBuilder: (context, index) {
              final payment = order.payments[index];
              return _buildPaymentMethodCard(payment);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentMethodCard(OrderPayment payment) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColor.success.withOpacity(0.05),
            AppColor.success.withOpacity(0.02),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColor.success.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: AppColor.success.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              _getPaymentIcon(payment.paymentMethodType),
              color: AppColor.success,
              size: 20,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  payment.paymentMethodName,
                  style: AppStyle.md.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.textPrimary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  payment.paymentMethodType,
                  style: AppStyle.sm.copyWith(color: AppColor.textSecondary),
                ),
                if (payment.splitType.isNotEmpty && payment.splitTotal > 1) ...[
                  const SizedBox(height: 4),
                  Text(
                    'Split ${payment.splitNumber}/${payment.splitTotal}',
                    style: AppStyle.xs.copyWith(color: AppColor.info),
                  ),
                ],
              ],
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                'Rp ${_formatCurrency(payment.amount)}',
                style: AppStyle.md.copyWith(
                  fontWeight: FontWeight.bold,
                  color: AppColor.success,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 4),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: _getPaymentStatusColor(
                    payment.status,
                  ).withOpacity(0.2),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  payment.status,
                  style: AppStyle.xs.copyWith(
                    color: _getPaymentStatusColor(payment.status),
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  bool _isDineIn() {
    final orderType = order.orderType
        .toLowerCase()
        .replaceAll('-', '')
        .replaceAll('_', '');
    return orderType == 'dinein' ||
        orderType == 'dine' ||
        orderType.contains('dinein');
  }

  bool _shouldShowTableNumber() {
    final orderType = order.orderType
        .toLowerCase()
        .replaceAll('-', '')
        .replaceAll('_', '')
        .replaceAll(' ', '');

    // Don't show table number for these order types
    final noTableTypes = [
      'takeaway',
      'takeout',
      'pickup',
      'delivery',
      'dinein',
    ];

    return !noTableTypes.any((type) => orderType.contains(type)) &&
        order.tableNumber.isNotEmpty;
  }

  String _formatCurrency(int amount) {
    return amount.toString().replaceAllMapped(
      RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]}.',
    );
  }

  String _formatDateTime(String dateTime) {
    // Simple date formatting - you might want to use intl package for better formatting
    return dateTime.split('T')[0];
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'completed':
        return AppColor.success;
      case 'pending':
        return AppColor.warning;
      case 'cancelled':
        return AppColor.error;
      default:
        return AppColor.info;
    }
  }

  IconData _getStatusIcon(String status) {
    switch (status.toLowerCase()) {
      case 'completed':
        return Icons.check_circle;
      case 'pending':
        return Icons.access_time;
      case 'cancelled':
        return Icons.cancel;
      default:
        return Icons.info;
    }
  }

  IconData _getPaymentIcon(String type) {
    switch (type.toLowerCase()) {
      case 'cash':
        return Icons.money;
      case 'card':
        return Icons.credit_card;
      case 'digital':
        return Icons.qr_code;
      default:
        return Icons.payment;
    }
  }

  Color _getPaymentStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'success':
        return AppColor.success;
      case 'pending':
        return AppColor.warning;
      case 'failed':
        return AppColor.error;
      default:
        return AppColor.info;
    }
  }

  String _getItemStatus(BuildContext context, OrderItem item) {
    // Logic untuk menentukan status item berdasarkan:
    // 1. Status order secara keseluruhan
    // 2. Jika ada field status di OrderItem model
    // 3. Waktu pembuatan vs waktu sekarang

    switch (order.status.toLowerCase()) {
      case 'completed':
        return context.lang.completed;
      case 'pending':
        return context.lang.pending;
      case 'cancelled':
        return context.lang.void_text;
      default:
        return context.lang.pending;
    }
  }

  Color _getItemStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'completed':
        return AppColor.success;
      case 'pending':
        return AppColor.warning;
      case 'cancelled':
        return AppColor.error;
      default:
        return AppColor.primary;
    }
  }
}

class TablePatternPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = AppColor.white.withOpacity(0.1)
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    // Draw decorative pattern
    for (int i = 0; i < 8; i++) {
      final offset = i * 20.0;
      canvas.drawLine(
        Offset(offset, 0),
        Offset(offset + size.height * 0.3, size.height),
        paint,
      );
    }

    // Draw subtle dots pattern
    final dotPaint = Paint()
      ..color = AppColor.white.withOpacity(0.05)
      ..style = PaintingStyle.fill;

    for (int x = 0; x < size.width; x += 30) {
      for (int y = 0; y < size.height; y += 30) {
        canvas.drawCircle(Offset(x.toDouble(), y.toDouble()), 2, dotPaint);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
