import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../config.dart';
import 'dart:convert';
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:latlong2/latlong.dart';
import 'package:google_fonts/google_fonts.dart';
import 'map.dart';
import '../beranda.dart';

class PaymentPage extends StatefulWidget {
  final int totalBill;
  final List<dynamic> cartItems;
  final Map<String, dynamic> userData;
  final double weight;
  final String deliveryType;
  final String estimationType;
  final Map<String, dynamic>? pickupData;

  const PaymentPage({
    super.key,
    required this.totalBill,
    required this.cartItems,
    required this.userData,
    required this.weight,
    required this.deliveryType,
    required this.estimationType,
    this.pickupData,
  });

  @override
  State<PaymentPage> createState() => _PaymentPageState();
}

class _PaymentPageState extends State<PaymentPage> {
  // --- Tailwind DESIGN TOKENS ---
  final Color primary = const Color(0xFF0058BE);
  final Color onPrimary = const Color(0xFFFFFFFF);
  final Color primaryContainer = const Color(0xFF2170E4);
  final Color background = const Color(0xFFF7F9FB);
  final Color surface = const Color(0xFFF7F9FB);
  final Color surfaceContainerLowest = const Color(0xFFFFFFFF);
  final Color surfaceContainerLow = const Color(0xFFF0F4F8);
  final Color onSurface = const Color(0xFF191C1E);
  final Color onSurfaceVariant = const Color(0xFF424754);
  final Color outlineVariant = const Color(0xFFC2C6D6);
  final Color outline = const Color(0xFF727785);
  final Color successGreen = const Color(0xFF10B981);
  final Color errorRed = const Color(0xFFBA1A1A);

  // State
  String selectedMethod = "Tunai";
  bool _isSubmitting = false;
  // ignore: unused_field
  bool _isLoadingFee = false;
  int change = 0;
  int _deliveryFee = 0;

  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]}.');
  }

  /// Membulatkan harga ke atas kelipatan 500
  int _roundTo500(int value) {
    return ((value / 500).ceil() * 500).toInt();
  }

  // Controllers
  final TextEditingController _cashReceivedController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _addressController = TextEditingController();

  LatLng? _selectedCoordinates;

  @override
  void initState() {
    super.initState();
    _cashReceivedController.text = "0";
    _calculateChange("0");

    if (widget.pickupData != null) {
      _nameController.text = widget.pickupData!['customer_name'] ?? '';
      _phoneController.text = widget.pickupData!['phone'] ?? '';
      _addressController.text = widget.pickupData!['address'] ?? '';

      if (widget.pickupData!['latitude'] != null &&
          widget.pickupData!['longitude'] != null) {
        _selectedCoordinates = LatLng(
          double.tryParse(widget.pickupData!['latitude'].toString()) ?? 0.0,
          double.tryParse(widget.pickupData!['longitude'].toString()) ?? 0.0,
        );
        _checkDeliveryFee(_selectedCoordinates!);
      }
    }
  }

  Future<void> _checkDeliveryFee(LatLng loc) async {
    setState(() => _isLoadingFee = true);
    try {
      final String? token = widget.userData['access_token'];
      final response = await http.post(
        Uri.parse("${AppConfig.baseUrl}/check-delivery-fee"),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
          "Authorization": "Bearer $token",
        },
        body: json.encode({
          "latitude": loc.latitude,
          "longitude": loc.longitude,
          "delivery_type": widget.deliveryType,
        }),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _deliveryFee =
              _roundTo500((data['delivery_fee'] as num?)?.toInt() ?? 0);
        });
        _calculateChange(_cashReceivedController.text);
      }
    } catch (e) {
      debugPrint("Error check delivery fee: $e");
    } finally {
      if (mounted) setState(() => _isLoadingFee = false);
    }
  }

  void _calculateChange(String value) {
    int received = int.tryParse(value.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0;
    int roundedTotal = _roundTo500(widget.totalBill + _deliveryFee);
    setState(() {
      change = received - roundedTotal;
      if (change < 0) change = 0;
    });
  }

  Future<void> _submitTransaction() async {
    if (_nameController.text.isEmpty || _phoneController.text.isEmpty) {
      _showSnackBar("Nama dan Nomor WA wajib diisi!", Colors.orange);
      return;
    }

    if (widget.deliveryType != 'none' && _addressController.text.isEmpty) {
      _showSnackBar(
          "Alamat lengkap wajib diisi untuk layanan driver!", Colors.orange);
      return;
    }

    if (selectedMethod == "Tunai") {
      int received = int.tryParse(
              _cashReceivedController.text.replaceAll(RegExp(r'[^0-9]'), '')) ??
          0;
      int roundedTotal = _roundTo500(widget.totalBill + _deliveryFee);

      if (received <= 0) {
        _showSnackBar("Masukkan nominal uang!", Colors.orange);
        return;
      }

      if (received < roundedTotal) {
        _showSnackBar(
            "Uang tidak cukup! Tagihan: Rp ${formatHarga(roundedTotal)}",
            Colors.red);
        return;
      }
    }

    setState(() => _isSubmitting = true);
    try {
      final String? token = widget.userData['access_token'];
      final response = await http.post(
        Uri.parse("${AppConfig.baseUrl}/transactions"),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
          "Authorization": "Bearer $token",
        },
        body: json.encode({
          "customer_name": _nameController.text.trim(),
          "phone": _phoneController.text.trim(),
          "address": widget.deliveryType != 'none'
              ? _addressController.text.trim()
              : null,
          "items": widget.cartItems
              .map((item) => {
                    "service_id": item['service_id'],
                    "service_name": item['service_name'],
                    "price": item['price'], // Note: this is subtotal price
                    "qty_or_weight": item['weight'],
                    "unit": item['unit'],
                    "subtotal": item['price'],
                    "estimation_name": item['estimation_name'],
                  })
              .toList(),
          "total_weight": widget.weight,
          "total_price": _roundTo500(widget.totalBill),
          "latitude": _selectedCoordinates?.latitude,
          "longitude": _selectedCoordinates?.longitude,
          "status": "ANTRIAN",
          "payment_method": selectedMethod == "Tunai"
              ? "CASH"
              : (selectedMethod == "QRIS" ? "QRIS" : "BAYAR NANTI"),
          "estimation_type": widget.estimationType,
          "delivery_type": widget.deliveryType,
          if (widget.pickupData != null && widget.pickupData!['id'] != null)
            "order_id": widget.pickupData!['id'],
          "cash_received": selectedMethod == "Tunai"
              ? (int.tryParse(_cashReceivedController.text
                      .replaceAll(RegExp(r'[^0-9]'), '')) ??
                  widget.totalBill)
              : (selectedMethod == "QRIS" ? widget.totalBill : 0),
          "cash_change": selectedMethod == "Tunai" ? change : 0,
        }),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        _showSnackBar("Transaksi Berhasil & WA Terkirim!", successGreen);

        try {
          final dbRef = FirebaseDatabase.instance.ref();
          await dbRef.child('laundry/screen_status').set("RESTART");
        } catch(e) {
          debugPrint("Failed to send RESTART command: $e");
        }

        await Future.delayed(const Duration(seconds: 1));
        if (mounted) {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(
              builder: (context) => BerandaPage(userData: widget.userData),
            ),
            (route) => false,
          );
        }
      } else {
        _showSnackBar(
            "Gagal simpan transaksi: ${response.statusCode}", Colors.red);
      }
    } catch (e) {
      _showSnackBar("Error koneksi: $e", Colors.red);
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  void _showSnackBar(String message, Color color) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Row(
          children: [
            Icon(
              color == successGreen
                  ? Icons.check_circle_outline
                  : Icons.error_outline_rounded,
              color: Colors.white,
              size: 28,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    color == successGreen ? "Berhasil" : "Peringatan",
                    style: GoogleFonts.inter(
                        fontWeight: FontWeight.w800,
                        fontSize: 14,
                        color: Colors.white),
                  ),
                  Text(
                    message,
                    style: GoogleFonts.inter(
                        fontSize: 12,
                        color: Colors.white.withOpacity(0.9),
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      behavior: SnackBarBehavior.floating,
      backgroundColor: color.withOpacity(0.95),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
        side: BorderSide(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      duration: const Duration(seconds: 3),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: background,
      appBar: _buildModernAppBar(),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildBillCard(),
            const SizedBox(height: 32),
            _buildSectionHeader("Data Pelanggan"),
            const SizedBox(height: 12),
            _buildCustomerForm(),
            if (widget.deliveryType != 'none') ...[
              const SizedBox(height: 24),
              _buildSectionHeader("Alamat"),
              const SizedBox(height: 12),
              _buildAddressForm(),
            ],
            const SizedBox(height: 24),
            _buildSectionHeader("Metode Pembayaran"),
            const SizedBox(height: 12),
            _buildPaymentMethodSection(),
            const SizedBox(height: 40),
          ],
        ),
      ),
      bottomNavigationBar: _buildBottomAction(),
    );
  }

  // --- WIDGET COMPONENTS ---

  PreferredSizeWidget _buildModernAppBar() {
    return AppBar(
      backgroundColor: Colors.white.withOpacity(0.95),
      elevation: 0,
      scrolledUnderElevation: 1,
      centerTitle: true,
      leading: IconButton(
        onPressed: () => Navigator.pop(context),
        icon:
            Icon(Icons.arrow_back_ios_new_rounded, color: onSurface, size: 20),
      ),
      title: Text("Konfirmasi Bayar",
          style: GoogleFonts.inter(
              color: onSurface, fontWeight: FontWeight.w700, fontSize: 18)),
    );
  }

  Widget _buildSectionHeader(String title) {
    return Text(title,
        style: GoogleFonts.inter(
            color: onSurface, fontSize: 16, fontWeight: FontWeight.w700));
  }

  Widget _buildBillCard() {
    // Tentukan label layanan driver
    String driverLabel;
    switch (widget.deliveryType) {
      case 'pickup':
        driverLabel = 'Pick-up';
        break;
      case 'delivery':
        driverLabel = 'Delivery';
        break;
      case 'both':
        driverLabel = 'Pick-up & Delivery';
        break;
      default:
        driverLabel = 'Ambil di Toko';
    }

    return Container(
      decoration: BoxDecoration(
        color: surfaceContainerLowest,
        border: Border.all(color: outlineVariant),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: primary.withOpacity(0.08),
              borderRadius:
                  const BorderRadius.vertical(top: Radius.circular(11)),
              border: Border(
                  bottom: BorderSide(color: outlineVariant.withOpacity(0.5))),
            ),
            child: Text(
              "RINCIAN PESANAN",
              textAlign: TextAlign.center,
              style: GoogleFonts.inter(
                fontSize: 12,
                fontWeight: FontWeight.w700,
                color: primary,
                letterSpacing: 1.5,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text("Layanan & Harga",
                    style: GoogleFonts.inter(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: onSurfaceVariant)),
                const SizedBox(height: 8),
                Container(
                  decoration: BoxDecoration(
                    color: surface,
                    border: Border.all(color: outlineVariant),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    children: widget.cartItems.asMap().entries.map((entry) {
                      int idx = entry.key;
                      var item = entry.value;
                      String qtyStr = item['unit'] == 'PCS'
                          ? "${item['weight'].toInt()} PCS"
                          : "${item['weight'].toStringAsFixed(3)} KG";
                      String namePart = "${item['service_name']} ($qtyStr)";
                      String pricePart = "Rp ${formatHarga(item['price'])}";
                      return Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 10),
                        decoration: BoxDecoration(
                          border: idx != widget.cartItems.length - 1
                              ? Border(
                                  bottom: BorderSide(
                                      color: outlineVariant.withOpacity(0.5)))
                              : null,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                                child: Text(namePart,
                                    style: GoogleFonts.inter(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                        color: onSurface))),
                            Text(pricePart,
                                style: GoogleFonts.inter(
                                    fontSize: 12,
                                    fontWeight: FontWeight.w600,
                                    color: onSurface)),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
                const SizedBox(height: 16),
                _buildReceiptRow("Opsi Pengiriman", driverLabel),
                if (widget.deliveryType != 'none') ...[
                  const SizedBox(height: 12),
                  _buildReceiptRow(
                    "Tarif Driver",
                    _selectedCoordinates == null
                        ? "Pilih Lokasi"
                        : (_deliveryFee > 0
                            ? "Rp ${formatHarga(_deliveryFee)}"
                            : "Gratis Ongkir"),
                    isHighlight:
                        _deliveryFee == 0 && _selectedCoordinates != null,
                  ),
                ],
                const SizedBox(height: 16),
                _buildDashedLine(),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text("Total Tagihan",
                        style: GoogleFonts.inter(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: primary)),
                    Text(
                        "Rp ${formatHarga(_roundTo500(widget.totalBill + _deliveryFee))}",
                        style: GoogleFonts.inter(
                            fontSize: 22,
                            fontWeight: FontWeight.w700,
                            color: primary,
                            letterSpacing: -0.5)),
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildReceiptRow(String label, String value,
      {bool isHighlight = false}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label,
            style: GoogleFonts.inter(
                color: onSurfaceVariant,
                fontSize: 12,
                fontWeight: FontWeight.w600)),
        const SizedBox(width: 16),
        Flexible(
          child: Text(value,
              textAlign: TextAlign.right,
              style: GoogleFonts.inter(
                  color: isHighlight ? successGreen : onSurface,
                  fontSize: 14,
                  fontWeight: FontWeight.w600)),
        ),
      ],
    );
  }

  Widget _buildDashedLine() {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final boxWidth = constraints.constrainWidth();
        const dashWidth = 5.0;
        const dashHeight = 1.0;
        final dashCount = (boxWidth / (2 * dashWidth)).floor();
        return Flex(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          direction: Axis.horizontal,
          children: List.generate(dashCount, (_) {
            return SizedBox(
              width: dashWidth,
              height: dashHeight,
              child: DecoratedBox(
                decoration: BoxDecoration(color: outlineVariant),
              ),
            );
          }),
        );
      },
    );
  }

  Widget _buildCustomerForm() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: outlineVariant, width: 1.0), // Dipertipis
        boxShadow: [
          BoxShadow(
              color: primary.withOpacity(0.06), // Diperlembut
              blurRadius: 20,
              offset: const Offset(0, 6))
        ],
      ),
      child: Column(
        children: [
          _buildInputField(
              "Nama Pelanggan", Icons.person_outline_rounded, _nameController),
          const SizedBox(height: 16),
          _buildInputField(
              "Nomor WhatsApp", Icons.phone_outlined, _phoneController,
              type: TextInputType.phone),
        ],
      ),
    );
  }

  Widget _buildAddressForm() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: outlineVariant, width: 1.0), // Dipertipis
        boxShadow: [
          BoxShadow(
              color: primary.withOpacity(0.06), // Diperlembut
              blurRadius: 20,
              offset: const Offset(0, 6))
        ],
      ),
      child: Column(
        children: [
          TextField(
            controller: _addressController,
            maxLines: 3,
            style: GoogleFonts.inter(
                color: onSurface, fontWeight: FontWeight.w500, fontSize: 14),
            decoration: InputDecoration(
              hintText: "Masukkan alamat lengkap beserta patokan...",
              hintStyle: GoogleFonts.inter(
                  color: onSurfaceVariant.withOpacity(0.5),
                  fontWeight: FontWeight.w400),
              filled: true,
              fillColor: background,
              contentPadding: const EdgeInsets.all(16),
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(color: outlineVariant, width: 1.0)),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(color: outlineVariant, width: 1.0)),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                  borderSide: BorderSide(color: primary, width: 1.0)),
            ),
          ),
          const SizedBox(height: 16),
          InkWell(
            onTap: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const MapPickerPage()),
              );
              if (result != null && result is LatLng) {
                setState(() {
                  _selectedCoordinates = result;
                });
                _checkDeliveryFee(result);
              }
            },
            borderRadius: BorderRadius.circular(12),
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
              decoration: BoxDecoration(
                color: _selectedCoordinates != null
                    ? successGreen.withOpacity(0.1)
                    : background,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: _selectedCoordinates != null
                      ? successGreen
                      : outlineVariant,
                  width: 1.0, // Dipertipis
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    _selectedCoordinates != null
                        ? Icons.location_on_rounded
                        : Icons.map_outlined,
                    size: 20,
                    color:
                        _selectedCoordinates != null ? successGreen : onSurface,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _selectedCoordinates != null
                        ? "Lokasi Sudah Disematkan"
                        : "Sematkan Lokasi di Map",
                    style: GoogleFonts.inter(
                      fontSize: 13,
                      fontWeight: FontWeight.w600,
                      color: _selectedCoordinates != null
                          ? successGreen
                          : onSurface,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInputField(
      String hint, IconData icon, TextEditingController ctrl,
      {TextInputType type = TextInputType.text}) {
    return TextField(
      controller: ctrl,
      keyboardType: type,
      style: GoogleFonts.inter(
          color: onSurface, fontWeight: FontWeight.w500, fontSize: 14),
      decoration: InputDecoration(
        prefixIcon: Icon(icon, color: onSurfaceVariant, size: 22),
        hintText: hint,
        hintStyle: GoogleFonts.inter(
            color: onSurfaceVariant.withOpacity(0.5),
            fontWeight: FontWeight.w400),
        filled: true,
        fillColor: background,
        contentPadding: const EdgeInsets.symmetric(vertical: 16),
        border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide:
                BorderSide(color: outlineVariant, width: 1.0)), // Dipertipis
        enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: outlineVariant, width: 1.0)),
        focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: primary, width: 1.0)),
      ),
    );
  }

  Widget _buildPaymentMethodSection() {
    return Column(
      children: [
        Row(
          children: [
            _methodOption("Tunai", Icons.payments_outlined),
            const SizedBox(width: 8),
            _methodOption("QRIS", Icons.qr_code_2_rounded),
            const SizedBox(width: 8),
            _methodOption("Bayar Nanti", Icons.history_rounded),
          ],
        ),
        const SizedBox(height: 16),
        if (selectedMethod == "Tunai")
          _buildCashInput()
        else if (selectedMethod == "QRIS")
          _buildQRISView()
        else
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
                color: Colors.orange.withOpacity(0.05),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.orange.withOpacity(0.2))),
            child: Row(
              children: [
                const Icon(Icons.info_outline_rounded, color: Colors.orange),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                      "Pembayaran akan ditagihkan saat cucian diambil di toko atau saat diantar oleh Driver.",
                      style: GoogleFonts.inter(
                          fontSize: 13,
                          color: Colors.orange.shade900,
                          fontWeight: FontWeight.w500)),
                ),
              ],
            ),
          ),
      ],
    );
  }

  Widget _methodOption(String label, IconData icon) {
    bool isSelected = selectedMethod == label;
    return Expanded(
      child: InkWell(
        onTap: () => setState(() => selectedMethod = label),
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 16),
          decoration: BoxDecoration(
            color: isSelected ? primary.withOpacity(0.08) : Colors.white,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
                color: isSelected ? primary : outlineVariant,
                width: isSelected ? 1.5 : 1.0), // Dipertipis
            boxShadow: [
              BoxShadow(
                  color: isSelected
                      ? primary.withOpacity(0.15)
                      : primary.withOpacity(0.04), // Diperlembut
                  blurRadius: 15,
                  offset: const Offset(0, 5))
            ],
          ),
          child: Column(
            children: [
              Icon(icon,
                  color: isSelected ? primary : onSurfaceVariant, size: 28),
              const SizedBox(height: 8),
              Text(label,
                  style: GoogleFonts.inter(
                      color: isSelected ? primary : onSurface,
                      fontWeight: FontWeight.w600,
                      fontSize: 14)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCashInput() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: outlineVariant, width: 1.0), // Dipertipis
          boxShadow: [
            BoxShadow(
                color: primary.withOpacity(0.06), // Diperlembut
                blurRadius: 20,
                offset: const Offset(0, 6))
          ]),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("Uang Diterima",
                  style: GoogleFonts.inter(
                      color: onSurface, fontWeight: FontWeight.w600)),
              Container(
                width: 140,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                    color: background,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(
                        color: outlineVariant, width: 1.0)), // Dipertipis
                child: TextField(
                  controller: _cashReceivedController,
                  onChanged: _calculateChange,
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.right,
                  style: GoogleFonts.inter(
                      fontWeight: FontWeight.w600,
                      color: primary,
                      fontSize: 16),
                  decoration: InputDecoration(
                      prefixText: "Rp ",
                      prefixStyle: GoogleFonts.inter(
                          color: onSurfaceVariant, fontWeight: FontWeight.w500),
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(vertical: 12)),
                ),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: Divider(color: outlineVariant, height: 1.0), // Dipertipis
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("Kembalian",
                  style: GoogleFonts.inter(
                      color: onSurface, fontWeight: FontWeight.w600)),
              Text("Rp ${formatHarga(change)}",
                  style: GoogleFonts.inter(
                      fontWeight: FontWeight.w600,
                      color: successGreen,
                      fontSize: 18)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQRISView() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(32),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: outlineVariant, width: 1.0),
          boxShadow: [
            BoxShadow(
                color: primary.withOpacity(0.06),
                blurRadius: 20,
                offset: const Offset(0, 6))
          ]),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                    color: outlineVariant, width: 1.0)),
            child: Image.asset(
              'assets/qris.png',
              width: 160,
              fit: BoxFit.contain,
            ),
          ),
          const SizedBox(height: 16),
          Text("Scan QR untuk pembayaran",
              style: GoogleFonts.inter(
                  color: onSurfaceVariant,
                  fontWeight: FontWeight.w500,
                  fontSize: 13)),
        ],
      ),
    );
  }

  Widget _buildBottomAction() {
    return Container(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
        border: Border(
            top: BorderSide(color: outlineVariant, width: 1.0)), // Dipertipis
        boxShadow: [
          BoxShadow(
              color: primary.withOpacity(0.06), // Diperlembut
              blurRadius: 24,
              offset: const Offset(0, -8))
        ],
      ),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          height: 56,
          child: ElevatedButton(
            onPressed: _isSubmitting ? null : _submitTransaction,
            style: ElevatedButton.styleFrom(
              backgroundColor: primary,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
              elevation: 0,
            ),
            child: _isSubmitting
                ? const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                        color: Colors.white, strokeWidth: 3))
                : Text("SIMPAN TRANSAKSI",
                    style: GoogleFonts.inter(
                        fontWeight: FontWeight.w700,
                        fontSize: 15,
                        letterSpacing: 0.5)),
          ),
        ),
      ),
    );
  }
}
