import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../../config.dart';
import 'dart:convert';
import 'package:google_fonts/google_fonts.dart';
import '../beranda.dart';
import '../../driver/beranda.dart' as driver_beranda;

class HomePaymentPage extends StatefulWidget {
  final dynamic order;
  final Map<String, dynamic> userData;

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

  @override
  State<HomePaymentPage> createState() => _HomePaymentPageState();
}

class _HomePaymentPageState extends State<HomePaymentPage> {
  // --- 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); // changed
  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;
  int change = 0;
  final TextEditingController _cashReceivedController = TextEditingController();

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

  void _calculateChange(String value) {
    int total = widget.order['total_price'] ?? widget.order['total'] ?? 0;
    int received = int.tryParse(value.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0;
    setState(() {
      change = received - total;
    });
  }

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

  Future<void> _submitPayment() async {
    if (selectedMethod == "Tunai") {
      int received = int.tryParse(
              _cashReceivedController.text.replaceAll(RegExp(r'[^0-9]'), '')) ??
          0;
      int total = widget.order['total_price'] ?? widget.order['total'] ?? 0;

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

      if (received < total) {
        _showSnackBar(
            "Uang tidak cukup! Tagihan: Rp ${formatHarga(total)}", errorRed);
        return;
      }
    }
    setState(() => _isSubmitting = true);
    try {
      String baseUrl = AppConfig.baseUrl;
      final String? token = widget.userData['access_token'];
      final int orderId = widget.order['id'];

      final response = await http.put(
        Uri.parse('$baseUrl/orders/$orderId/update-status'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: json.encode({
          'payment_method': selectedMethod == "Tunai" ? "CASH" : "QRIS",
          'cash_received': selectedMethod == "Tunai"
              ? (int.tryParse(_cashReceivedController.text
                      .replaceAll(RegExp(r'[^0-9]'), '')) ??
                  (widget.order['total_price'] ?? widget.order['total'] ?? 0))
              : (widget.order['total_price'] ?? widget.order['total'] ?? 0),
        }),
      );

      if (response.statusCode == 200) {
        _showSnackBar("Pelunasan Berhasil!", successGreen);
        await Future.delayed(const Duration(seconds: 1));
        if (mounted) {
          final String userRole = widget.userData['user']?['role'] ?? 'staf';
          if (userRole == 'driver') {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder: (context) =>
                    driver_beranda.BerandaPage(userData: widget.userData),
              ),
              (route) => false,
            );
          } else {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder: (context) => BerandaPage(userData: widget.userData),
              ),
              (route) => false,
            );
          }
        }
      } else {
        _showSnackBar(
            "Gagal memproses pelunasan: ${response.statusCode}", errorRed);
      }
    } catch (e) {
      _showSnackBar("Error koneksi: $e", errorRed);
    } 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),
    ));
  }

  String _formatWeightInString(String input) {
    return input.replaceAllMapped(RegExp(r'\(([\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)";
      return "(${val.toStringAsFixed(3)} $unit)"; // updated to 3 decimals
    });
  }

  @override
  Widget build(BuildContext context) {
    int total = widget.order['total_price'] ?? widget.order['total'] ?? 0;

    return Scaffold(
      backgroundColor: background,
      appBar: _buildAppBar(),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _buildOrderSummary(total),
                    const SizedBox(height: 24),
                    _buildPaymentMethods(),
                    const SizedBox(height: 16),
                    if (selectedMethod == "Tunai")
                      _buildCashPanel(total)
                    else
                      _buildQRISPanel(),
                    const SizedBox(height: 40), // extra padding for scrolling
                  ],
                ),
              ),
            ),
            _buildBottomAction(),
          ],
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white.withOpacity(0.9),
      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("Pelunasan",
          style: GoogleFonts.inter(
              color: onSurface, fontWeight: FontWeight.w700, fontSize: 18)),
    );
  }

  Widget _buildOrderSummary(int total) {
    int deliveryFee =
        int.tryParse(widget.order['delivery_fee']?.toString() ?? "0") ?? 0;

    // Parse multiple services if needed (like in order_list)
    String rawSubtitle = widget.order['service_name']?.toString() ??
        widget.order['subtitle']?.toString() ??
        "-";

    // Ekstrak ongkir jika berasal dari API dashboard (tergabung di subtitle)
    if (deliveryFee == 0 && rawSubtitle.toLowerCase().contains('ongkir')) {
      final ongkirMatch =
          RegExp(r'Ongkir:\s*Rp\s*([\d\.]+)').firstMatch(rawSubtitle);
      if (ongkirMatch != null) {
        deliveryFee =
            int.tryParse(ongkirMatch.group(1)!.replaceAll('.', '')) ?? 0;
      }
    }

    String deliveryType =
        widget.order['delivery_type']?.toString().toLowerCase() ?? 'none';
    if (deliveryType == 'none' && deliveryFee > 0) {
      deliveryType =
          'delivery'; // Asumsi delivery jika ada ongkir tapi tipe kosong
    }

    String driverLabel = "Ambil di Toko";
    if (deliveryType == 'pickup' || deliveryType == 'dijemput') {
      driverLabel = "Pick-up";
    } else if (deliveryType == 'delivery' || deliveryType == 'diantar') {
      driverLabel = "Delivery";
    } else if (deliveryType == 'both' || deliveryType == 'keduanya') {
      driverLabel = "Pick-up & Delivery";
    }

    List<String> serviceItems = rawSubtitle
        .split(RegExp(r' \+ |\n'))
        .where((e) => !e
            .toLowerCase()
            .contains('ongkir')) // Hapus ongkir dari list layanan
        .map((e) => _formatWeightInString(e))
        .toList();

    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: [
                _buildSummaryRow(
                    "Pelanggan",
                    widget.order['customer_name']?.toString() ??
                        widget.order['title']?.toString() ??
                        "-"),
                const SizedBox(height: 12),
                _buildSummaryRow("ID Pesanan",
                    "#${widget.order['order_number'] ?? widget.order['id'] ?? 'ACT'}"),
                const SizedBox(height: 16),
                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: serviceItems.asMap().entries.map((entry) {
                      int idx = entry.key;
                      String item = entry.value;
                      List<String> parts = item.split('||');
                      String namePart = parts[0].trim();
                      String pricePart = parts.length > 1
                          ? "Rp ${formatHarga(parts[1].trim())}"
                          : "";

                      // Jika harga per jasa tidak tersedia dari API Beranda,
                      // hitung otomatis (Total Harga - Ongkos Kirim) jika hanya ada 1 jasa
                      if (pricePart.isEmpty && serviceItems.length == 1) {
                        int servicesPrice = total - deliveryFee;
                        if (servicesPrice > 0) {
                          pricePart = "Rp ${formatHarga(servicesPrice)}";
                        }
                      }

                      return Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 10),
                        decoration: BoxDecoration(
                          border: idx != serviceItems.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),
                _buildSummaryRow("Opsi Driver", driverLabel),
                if (deliveryFee > 0) ...[
                  const SizedBox(height: 12),
                  _buildSummaryRow(
                      "Ongkos Kirim", "Rp ${formatHarga(deliveryFee)}"),
                ],
                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(total)}",
                        style: GoogleFonts.inter(
                            fontSize: 22,
                            fontWeight: FontWeight.w700,
                            color: primary,
                            letterSpacing: -0.5)),
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

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

  Widget _buildDashedLine() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final boxWidth = constraints.constrainWidth();
        const dashWidth = 12.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 _buildPaymentMethods() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("Metode Pelunasan",
            style: GoogleFonts.inter(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: onSurfaceVariant)),
        const SizedBox(height: 12),
        Row(
          children: [
            _methodOption("Tunai", Icons.payments_outlined),
            const SizedBox(width: 16),
            _methodOption("QRIS", Icons.qr_code_2_rounded),
          ],
        )
      ],
    );
  }

  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),
            boxShadow: [
              BoxShadow(
                  color: isSelected
                      ? primary.withOpacity(0.15)
                      : primary.withOpacity(0.04),
                  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 _buildCashPanel(int total) {
    return Container(
      padding: const EdgeInsets.all(20),
      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: [
          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)),
                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),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("Kembalian",
                  style: GoogleFonts.inter(
                      color: onSurface, fontWeight: FontWeight.w600)),
              Text(change < 0 ? "Rp 0" : "Rp ${formatHarga(change)}",
                  style: GoogleFonts.inter(
                      fontWeight: FontWeight.w600,
                      color: change < 0
                          ? onSurfaceVariant.withOpacity(0.5)
                          : successGreen,
                      fontSize: 18)),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildQRISPanel() {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(top: 16),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: const Color(0xFFF7F9FB),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: const Color(0xFFE6E8EA)),
      ),
      child: Column(
        children: [
          Container(
            width: 200,
            height: 200,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: const Color(0xFFE6E8EA)),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.asset(
                'assets/qris.png',
                fit: BoxFit.contain,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Text(
            "Scan QRIS untuk membayar",
            style: GoogleFonts.inter(
              fontSize: 13,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF424754),
            ),
          ),
        ],
      ),
    );
  }

  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)),
        boxShadow: [
          BoxShadow(
              color: primary.withOpacity(0.06),
              blurRadius: 24,
              offset: const Offset(0, -8))
        ],
      ),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          height: 54,
          child: ElevatedButton(
            onPressed: _isSubmitting ? null : _submitPayment,
            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("SELESAIKAN",
                    style: GoogleFonts.inter(
                        color: Colors.white,
                        fontWeight: FontWeight.w700,
                        fontSize: 15,
                        letterSpacing: 0.5)),
          ),
        ),
      ),
    );
  }
}
