import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../../config.dart';
import 'dart:async';

import 'package:google_fonts/google_fonts.dart';
import 'payments.dart';

class OrderListPage extends StatefulWidget {
  final String initialFilter;
  final Map<String, dynamic> userData;

  const OrderListPage({
    super.key,
    required this.initialFilter,
    required this.userData,
  });

  @override
  State<OrderListPage> createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage> {
  late String _currentFilter;

  // --- UNIFIED DESIGN TOKENS ---
  final Color bgBackground = const Color(0xFFf7f9fb);
  final Color surfaceLowest = const Color(0xFFffffff);
  final Color surfaceLow = const Color(0xFFf2f4f6);
  final Color outlineVariant = const Color(0xFFc2c6d6);
  final Color outlineColor = const Color(0xFF727785);
  final Color primaryColor = const Color(0xFF0058be);
  final Color primaryContainer = const Color(0xFF2170e4);
  final Color errorColor = const Color(0xFFba1a1a);
  final Color secondaryContainer = const Color(0xFFc3ecd7);
  final Color onSecondaryContainer = const Color(0xFF476c5b);
  final Color onSurface = const Color(0xFF191c1e);
  final Color onSurfaceVariant = const Color(0xFF424754);
  final Color surfaceContainerHigh = const Color(0xFFe6e8ea);
  final Color surfaceContainer = const Color(0xFFeceef0);

  String formatHarga(dynamic value) {
    if (value == null) return "0";
    String val = value.toString();
    RegExp reg = RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
    return val.replaceAllMapped(reg, (Match m) => '${m[1]}.');
  }

  final TextEditingController _searchController = TextEditingController();
  List<dynamic> allOrders = [];
  List<dynamic> filteredOrders = [];
  bool isLoading = true;
  Timer? _timer;
  int _fetchGeneration = 0; // untuk menghindari race condition saat ganti filter

  @override
  void initState() {
    super.initState();
    _currentFilter = widget.initialFilter;
    fetchOrders();
    _searchController.addListener(_onSearchChanged);
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      if (mounted) {
        fetchOrders(showLoading: false);
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    super.dispose();
  }

  void _onSearchChanged() {
    String query = _searchController.text.toLowerCase();
    setState(() {
      filteredOrders = allOrders.where((order) {
        String name = (order['customer_name'] ?? "").toString().toLowerCase();
        String orderNum = (order['order_number'] ?? order['id'] ?? "")
            .toString()
            .toLowerCase();
        return name.contains(query) || orderNum.contains(query);
      }).toList();
    });
  }

  String _calculateRemainingTime(String? estimationTime) {
    if (estimationTime == null || estimationTime.isEmpty) return "Belum diatur";
    try {
      DateTime target = DateTime.parse(estimationTime);
      DateTime now = DateTime.now();
      Duration diff = target.difference(now);
      if (diff.isNegative) return "Waktu Habis!";
      if (diff.inHours >= 24) return "${(diff.inHours / 24).ceil()} hari lagi";
      String hours = diff.inHours.toString().padLeft(2, '0');
      String minutes = (diff.inMinutes % 60).toString().padLeft(2, '0');
      return "$hours jam $minutes menit lagi";
    } catch (e) {
      return "Format error";
    }
  }

  Future<void> fetchOrders({bool showLoading = true}) async {
    if (!mounted) return;
    // Naikkan generation agar response lama bisa diabaikan (race condition fix)
    final int myGeneration = ++_fetchGeneration;
    if (showLoading) setState(() => isLoading = true);
    String baseUrl = AppConfig.baseUrl;
    final String? token = widget.userData['access_token'];
    // Simpan filter yang sedang aktif saat request dikirim
    final String requestedFilter = _currentFilter;

    try {
      final response = await http.get(
        Uri.parse('$baseUrl/orders/status/${requestedFilter.toUpperCase()}'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
      );

      // Buang response jika ada request yang lebih baru (filter sudah diganti)
      if (myGeneration != _fetchGeneration) return;

      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = json.decode(response.body);
        if (mounted) {
          setState(() {
            List<dynamic> fetchedOrders = responseData['data'] ?? [];
            fetchedOrders.sort((a, b) {
              int priority(String type) {
                String t = type.toLowerCase();
                if (t.contains('kilat')) return 1;
                if (t.contains('ekspres') || t.contains('express')) return 2;
                return 3;
              }

              int pA = priority((a['estimation_type'] ?? '').toString());
              int pB = priority((b['estimation_type'] ?? '').toString());
              if (pA != pB) return pA.compareTo(pB);

              final fallbackTime = DateTime(2100, 1, 1);
              DateTime parseTime(dynamic timeStr) {
                if (timeStr == null || timeStr.toString().isEmpty) {
                  return fallbackTime;
                }
                return DateTime.tryParse(timeStr.toString()) ?? fallbackTime;
              }

              DateTime timeA = parseTime(a['estimation_time']);
              DateTime timeB = parseTime(b['estimation_time']);

              int comp = timeA.compareTo(timeB);
              if (comp != 0) return comp;
              return (a['id'] as int)
                  .compareTo(b['id'] as int); // tertiary sort oldest first
            });
            allOrders = fetchedOrders;
            // Pertahankan filter pencarian yang sedang aktif
            String query = _searchController.text.toLowerCase();
            if (query.isEmpty) {
              filteredOrders = allOrders;
            } else {
              filteredOrders = allOrders.where((order) {
                String name =
                    (order['customer_name'] ?? "").toString().toLowerCase();
                String orderNum = (order['order_number'] ?? order['id'] ?? "")
                    .toString()
                    .toLowerCase();
                return name.contains(query) || orderNum.contains(query);
              }).toList();
            }
            isLoading = false;
          });
        }
      } else {
        if (myGeneration == _fetchGeneration && mounted) {
          setState(() => isLoading = false);
        }
      }
    } catch (e) {
      if (myGeneration == _fetchGeneration && mounted) {
        setState(() => isLoading = false);
      }
    }
  }

  Future<void> updateOrderStatus(int id,
      {Map<String, dynamic>? paymentData}) async {
    String baseUrl = AppConfig.baseUrl;
    final String? token = widget.userData['access_token'];
    try {
      final response = await http.put(
        Uri.parse('$baseUrl/orders/$id/update-status'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: paymentData != null ? json.encode(paymentData) : null,
      );
      if (response.statusCode == 200) fetchOrders();
    } catch (e) {
      debugPrint("Update Error: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgBackground,
      appBar: _buildAppBar(),
      body: Column(
        children: [
          _buildSearchBar(),
          _buildFilterChips(),
          const SizedBox(height: 12),
          Expanded(
            child: isLoading
                ? Center(
                    child: CircularProgressIndicator(
                        color: primaryColor, strokeWidth: 3))
                : RefreshIndicator(
                    onRefresh: fetchOrders,
                    color: primaryColor,
                    child: filteredOrders.isEmpty
                        ? _buildEmptyState()
                        : ListView.separated(
                            padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
                            itemCount: filteredOrders.length,
                            separatorBuilder: (_, __) =>
                                const SizedBox(height: 16),
                            itemBuilder: (context, i) =>
                                _buildOrderCard(filteredOrders[i]),
                          ),
                  ),
          ),
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: surfaceLowest,
      elevation: 0,
      centerTitle: false,
      title: Text("Daftar Pesanan",
          style: GoogleFonts.inter(
              color: onSurface, fontWeight: FontWeight.w600, fontSize: 18)),
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: primaryColor, size: 24),
        onPressed: () => Navigator.pop(context),
      ),
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1.0),
        child: Container(color: surfaceContainerHigh, height: 1.0),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
      child: Container(
        decoration: BoxDecoration(
          color: surfaceLowest,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: outlineVariant.withOpacity(0.3)),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.02),
              blurRadius: 4,
              offset: const Offset(0, 2),
            )
          ],
        ),
        child: TextField(
          controller: _searchController,
          decoration: InputDecoration(
            hintText: "Cari pelanggan atau no pesanan...",
            hintStyle: GoogleFonts.inter(fontSize: 13, color: outlineColor),
            prefixIcon: Icon(Icons.search, color: outlineColor, size: 20),
            border: InputBorder.none,
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          ),
          style: GoogleFonts.inter(fontSize: 13),
        ),
      ),
    );
  }

  Widget _buildFilterChips() {
    final filters = ['Antrian', 'Proses', 'Selesai'];
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 12),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: filters.map((filter) {
            bool active = _currentFilter.toLowerCase() == filter.toLowerCase();
            return GestureDetector(
              onTap: () {
                setState(() => _currentFilter = filter);
                fetchOrders();
              },
              child: Container(
                margin: const EdgeInsets.only(right: 8),
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                decoration: BoxDecoration(
                  color: active ? primaryColor : surfaceContainerHigh,
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: active
                      ? [
                          BoxShadow(
                              color: primaryColor.withOpacity(0.2),
                              blurRadius: 12,
                              offset: const Offset(0, 4))
                        ]
                      : null,
                ),
                alignment: Alignment.center,
                child: Text(
                  filter,
                  style: GoogleFonts.inter(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: active ? Colors.white : onSurfaceVariant,
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildOrderCard(dynamic order) {
    String title = order['customer_name']?.toString() ?? "Pelanggan";

    String rawSubtitle = order['service_name']?.toString() ?? "-";
    String formatWeightInString(String input) {
      return input.replaceAllMapped(RegExp(r'\((\d+\.?\d*)\s*([a-zA-Z]+)\)'),
          (match) {
        double val = double.tryParse(match.group(1) ?? "0") ?? 0;
        String unit = match.group(2) ?? "Kg";
        if (unit.toUpperCase() == 'PCS') return "(${val.toInt()} $unit)";

        String valStr = val.toStringAsFixed(3);

        return "($valStr $unit)";
      });
    }

    List<String> serviceItems = rawSubtitle
        .split(RegExp(r' \+ |\n'))
        .map((e) => formatWeightInString(e))
        .toList();

    String status = order['status']?.toString().toUpperCase() ?? "PROSES";
    String orderId = "#${order['order_number'] ?? order['id'] ?? 'ACT'}";
    String phone = order['phone']?.toString() ?? "-";

    String price = "Rp 0";
    if (order['total_price'] != null) {
      price = "Rp ${formatHarga(order['total_price'])}";
    }

    String paymentMethod =
        (order['payment_method'] ?? "").toString().toUpperCase();
    double cashReceived =
        num.tryParse(order['cash_received']?.toString() ?? "0")?.toDouble() ??
            0.0;
    bool isPaid = !(paymentMethod == "BAYAR NANTI" && cashReceived == 0);

    String deliveryType =
        order['delivery_type']?.toString().toLowerCase() ?? "none";
    String estimasiTipe = order['estimation_type']?.toString() ?? "Reguler";
    String estimasiWaktu = _calculateRemainingTime(order['estimation_time']);

    if (status == 'MENUNGGU JEMPUT') status = 'PICKUP';
    if (status == 'JEMPUTAN TIBA') status = 'DI TOKO';

    // Format delivery label
    String deliveryLabel = "Drop-off";
    IconData deliveryIcon = Icons.store;
    if (deliveryType == 'diantar' || deliveryType == 'delivery') {
      deliveryLabel = "Delivery";
      deliveryIcon = Icons.moped;
    } else if (deliveryType == 'keduanya' ||
        deliveryType == 'both' ||
        deliveryType == 'dijemput' ||
        deliveryType == 'pickup') {
      deliveryLabel = deliveryType == 'dijemput' || deliveryType == 'pickup'
          ? "Pick Up"
          : "Pick Up & Delivery";
      deliveryIcon = Icons.moped;
    }

    bool hasDriverService = deliveryLabel != "Drop-off";

    Color paymentColor = isPaid ? onSecondaryContainer : errorColor;
    Color paymentBg = isPaid ? secondaryContainer : errorColor.withOpacity(0.1);
    String paymentText = isPaid ? "LUNAS" : "BELUM BAYAR";

    String buttonText = "Proses";
    if (status == 'ANTRIAN' || status == 'PICKUP') {
      buttonText = "Proses";
    } else if (status == 'PROSES') {
      buttonText = "Selesai";
    } else if (status == 'SELESAI') {
      buttonText = (deliveryType == 'delivery' ||
              deliveryType == 'both' ||
              deliveryType == 'diantar' ||
              deliveryType == 'keduanya')
          ? "Delivery"
          : "Diambil";
    } else if (status == 'DI DRIVER') {
        buttonText = "Selesai";
    }

    String address = order['address']?.toString() ?? "";
    if (address.isEmpty) address = "Alamat tidak tersedia";

    return Container(
      decoration: BoxDecoration(
        color: surfaceLowest,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: outlineVariant.withOpacity(0.5)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 8,
            offset: const Offset(0, 2),
          )
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(orderId,
                              style: GoogleFonts.inter(
                                  fontSize: 11,
                                  fontWeight: FontWeight.bold,
                                  color: primaryColor,
                                  letterSpacing: -0.2)),
                          const SizedBox(height: 2),
                          Text(title,
                              style: GoogleFonts.inter(
                                  fontSize: 18,
                                  fontWeight: FontWeight.w600,
                                  color: onSurface),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis),
                          const SizedBox(height: 2),
                          Row(
                            children: [
                              Icon(Icons.call, size: 14, color: outlineColor),
                              const SizedBox(width: 4),
                              Text(phone,
                                  style: GoogleFonts.inter(
                                      fontSize: 11, color: outlineColor)),
                            ],
                          )
                        ],
                      ),
                    ),
                    const SizedBox(width: 8),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 10, vertical: 4),
                          decoration: BoxDecoration(
                            color: paymentBg,
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                                color: paymentColor.withOpacity(0.2)),
                          ),
                          child: Text(paymentText,
                              style: GoogleFonts.inter(
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                  color: paymentColor)),
                        ),
                        const SizedBox(height: 8),
                        if (hasDriverService)
                          Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: isPaid
                                  ? surfaceContainer
                                  : secondaryContainer.withOpacity(0.5),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(deliveryIcon,
                                    size: 14,
                                    color: isPaid
                                        ? onSurfaceVariant
                                        : onSecondaryContainer),
                                const SizedBox(width: 4),
                                Text(deliveryLabel,
                                    style: GoogleFonts.inter(
                                        fontSize: 10,
                                        fontWeight: FontWeight.w600,
                                        color: isPaid
                                            ? onSurfaceVariant
                                            : onSecondaryContainer)),
                              ],
                            ),
                          )
                      ],
                    )
                  ],
                ),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: surfaceLow.withOpacity(0.5),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: outlineVariant.withOpacity(0.3)),
                  ),
                  child: Column(
                    children: [
                      ...serviceItems.map((item) {
                        List<String> parts = item.split('||');
                        String namePart = parts[0];
                        String pricePart = parts.length > 1
                            ? "Rp ${formatHarga(parts[1])}"
                            : "";
                        return Padding(
                          padding: const EdgeInsets.only(bottom: 8.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Icon(Icons.dry_cleaning,
                                        size: 18, color: primaryColor),
                                    const SizedBox(width: 8),
                                    Expanded(
                                        child: Text(namePart,
                                            style: GoogleFonts.inter(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600,
                                                color: onSurface),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis)),
                                  ],
                                ),
                              ),
                              if (pricePart.isNotEmpty) ...[
                                const SizedBox(width: 8),
                                Text(pricePart,
                                    style: GoogleFonts.inter(
                                        fontSize: 13,
                                        fontWeight: FontWeight.bold,
                                        color: primaryColor)),
                              ]
                            ],
                          ),
                        );
                      }),
                      if ((num.tryParse(
                                  order['delivery_fee']?.toString() ?? "0") ??
                              0) >
                          0)
                        Padding(
                          padding: const EdgeInsets.only(bottom: 8.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Icon(Icons.two_wheeler,
                                        size: 18, color: Colors.teal.shade700),
                                    const SizedBox(width: 8),
                                    Expanded(
                                        child: Text("Tarif Driver",
                                            style: GoogleFonts.inter(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600,
                                                color: onSurface))),
                                  ],
                                ),
                              ),
                              const SizedBox(width: 8),
                              Text("Rp ${formatHarga(order['delivery_fee'])}",
                                  style: GoogleFonts.inter(
                                      fontSize: 13,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.teal.shade700)),
                            ],
                          ),
                        ),
                      const SizedBox(height: 10),
                      Divider(
                          height: 1,
                          thickness: 1,
                          color: outlineVariant.withOpacity(0.3)),
                      const SizedBox(height: 10),
                      Row(
                        children: [
                          Row(
                            children: [
                              Icon(Icons.bolt,
                                  size: 14, color: onSurfaceVariant),
                              const SizedBox(width: 4),
                              Text(estimasiTipe,
                                  style: GoogleFonts.inter(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: onSurfaceVariant)),
                            ],
                          ),
                          const SizedBox(width: 16),
                          Row(
                            children: [
                              Icon(Icons.schedule,
                                  size: 14,
                                  color: estimasiWaktu.contains('Habis')
                                      ? errorColor
                                      : onSurfaceVariant),
                              const SizedBox(width: 4),
                              Text(estimasiWaktu,
                                  style: GoogleFonts.inter(
                                      fontSize: 11,
                                      fontWeight: FontWeight.w600,
                                      color: estimasiWaktu.contains('Habis')
                                          ? errorColor
                                          : onSurfaceVariant)),
                            ],
                          ),
                        ],
                      )
                    ],
                  ),
                ),
                if (hasDriverService) ...[
                  const SizedBox(height: 12),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(top: 2),
                        child: Icon(Icons.location_on,
                            size: 16, color: outlineColor),
                      ),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(address,
                            style: GoogleFonts.inter(
                                fontSize: 11, color: outlineColor),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis),
                      )
                    ],
                  )
                ]
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: surfaceLowest,
              border: Border(
                  top: BorderSide(color: outlineVariant.withOpacity(0.3))),
              borderRadius:
                  const BorderRadius.vertical(bottom: Radius.circular(16)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("TAGIHAN",
                        style: GoogleFonts.inter(
                            fontSize: 10,
                            fontWeight: FontWeight.w800,
                            color: outlineColor,
                            letterSpacing: 1.0)),
                    Text(price,
                        style: GoogleFonts.inter(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: onSurface)),
                  ],
                ),
                if (status != 'DIAMBIL' && status != 'DITERIMA' && status != 'TIBA DI TOKO')
                  ElevatedButton(
                    onPressed: () async {
                      bool isDelivery = (deliveryType == 'delivery' ||
                          deliveryType == 'both' ||
                          deliveryType == 'diantar' ||
                          deliveryType == 'keduanya');

                      if (status == 'SELESAI' && !isPaid && !isDelivery) {
                        final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => HomePaymentPage(
                              order: order,
                              userData: widget.userData,
                            ),
                          ),
                        );
                        if (result == true) fetchOrders();
                        return;
                      }

                      String dialogTitle = "Lanjutkan Pesanan?";
                      String dialogContent =
                          "Apakah Anda yakin ingin melanjutkan pesanan ini ke tahap selanjutnya?";

                      if (status == 'SELESAI') {
                        if (isDelivery) {
                          dialogTitle = "Tugaskan ke Driver?";
                          dialogContent =
                              "Pesanan ini akan diteruskan ke tugas Driver untuk diantar. Lanjutkan?";
                        } else {
                          dialogTitle = "Pesanan Diambil?";
                          dialogContent =
                              "Apakah pesanan ini akan diserahkan ke pelanggan? Status akan menjadi Diambil.";
                        }
                      } else if (status == 'PROSES') {
                        dialogTitle = "Selesaikan Cucian?";
                        dialogContent =
                            "Apakah proses cuci sudah selesai dan siap untuk dikemas/diambil?";
                      } else if (status == 'ANTRIAN' || status == 'PICKUP') {
                        dialogTitle = "Mulai Proses?";
                        dialogContent =
                            "Apakah Anda ingin mulai memproses pesanan ini sekarang?";
                      }

                      showDialog(
                        context: context,
                        builder: (ctx) => AlertDialog(
                          backgroundColor: surfaceLowest,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16)),
                          title: Text(dialogTitle,
                              style: GoogleFonts.inter(
                                  fontWeight: FontWeight.w700,
                                  color: onSurface)),
                          content: Text(dialogContent,
                              style:
                                  GoogleFonts.inter(color: onSurfaceVariant)),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.pop(ctx),
                              child: Text("Batal",
                                  style: GoogleFonts.inter(
                                      color: outlineColor,
                                      fontWeight: FontWeight.w600)),
                            ),
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: primaryColor,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(8)),
                              ),
                              onPressed: () {
                                Navigator.pop(ctx);
                                updateOrderStatus(order['id']);
                              },
                              child: Text("Ya, Lanjutkan",
                                  style: GoogleFonts.inter(
                                      fontWeight: FontWeight.w600)),
                            ),
                          ],
                        ),
                      );
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                      foregroundColor: Colors.white,
                      elevation: 0,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 8),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10)),
                    ),
                    child: Row(
                      children: [
                        Text(buttonText,
                            style: GoogleFonts.inter(
                                fontSize: 12, fontWeight: FontWeight.w600)),
                        const SizedBox(width: 6),
                        const Icon(Icons.arrow_forward, size: 16),
                      ],
                    ),
                  )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.inventory_2_outlined,
              size: 48, color: outlineColor.withOpacity(0.2)),
          const SizedBox(height: 16),
          Text("Belum ada pesanan",
              style: GoogleFonts.inter(
                  color: outlineColor, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}
