import 'package:flutter/material.dart';

// ── Brand tokens (shared design system) ──────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberGlow = Color(0x33FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
}

// ── Data model ────────────────────────────────────────────────────────────────
class PaymentOverviewLineItem {
  final String label;
  final double amount;
  PaymentOverviewLineItem({required this.label, required this.amount});
}

class PaymentOverviewData {
  final String addressSummary;
  final String serviceSummary;
  final double subtotal;
  final double serviceFee;
  final double deliveryFee;
  final double total;
  final double pointsDiscount;
  final int pointsUsed;
  /// Optional breakdown (e.g. cylinder + gas kit add-ons). When set, these rows are shown instead of a single "Subtotal" row.
  final List<PaymentOverviewLineItem>? lineItems;

  PaymentOverviewData({
    required this.addressSummary,
    required this.serviceSummary,
    required this.subtotal,
    required this.serviceFee,
    required this.deliveryFee,
    required this.total,
    this.pointsDiscount = 0,
    this.pointsUsed = 0,
    this.lineItems,
  });
}

// ── Widget ────────────────────────────────────────────────────────────────────
class PaymentOverview extends StatelessWidget {
  const PaymentOverview({
    super.key,
    required this.data,
    required this.onMakePayment,
    this.onCompleteOrder,
  });

  final PaymentOverviewData data;
  final VoidCallback onMakePayment;
  /// When cash to pay is 0 (100% points), this is used and button shows "COMPLETE ORDER" instead of opening payment.
  final VoidCallback? onCompleteOrder;

  String _fmt(double v) {
    // Format with thousands separator: 45000 → 45,000
    final parts = v.toStringAsFixed(0).split('');
    final buf = StringBuffer();
    for (int i = 0; i < parts.length; i++) {
      if (i > 0 && (parts.length - i) % 3 == 0) buf.write(',');
      buf.write(parts[i]);
    }
    return '${buf.toString()} UGX';
  }

  static String _fmtPoints(int n) {
    if (n < 1000) return '$n';
    final s = n.toString();
    final buf = StringBuffer();
    for (int i = 0; i < s.length; i++) {
      if (i > 0 && (s.length - i) % 3 == 0) buf.write(',');
      buf.write(s[i]);
    }
    return buf.toString();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: _Brand.amber.withOpacity(0.2), width: 1.5),
        boxShadow: [
          BoxShadow(
            color: _Brand.amber.withOpacity(0.06),
            blurRadius: 24,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // ── Header ──────────────────────────────────────────────────────
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
            decoration: const BoxDecoration(
              color: _Brand.amberGlow,
              borderRadius: BorderRadius.vertical(top: Radius.circular(17)),
              border: Border(
                bottom: BorderSide(color: Color(0x44FF9500), width: 1),
              ),
            ),
            child: Row(
              children: [
                const Icon(Icons.receipt_long_rounded,
                    color: _Brand.amber, size: 18),
                const SizedBox(width: 8),
                const Text(
                  'PAYMENT OVERVIEW',
                  style: TextStyle(
                    color: _Brand.amber,
                    fontSize: 11,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 2,
                  ),
                ),
              ],
            ),
          ),

          Padding(
            padding: const EdgeInsets.all(18),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // ── Delivery details ───────────────────────────────────
                _DetailRow(
                  icon: Icons.location_on_rounded,
                  label: 'Address',
                  value: data.addressSummary,
                ),
                const SizedBox(height: 10),
                _DetailRow(
                  icon: Icons.local_gas_station_rounded,
                  label: 'Service',
                  value: data.serviceSummary,
                ),

                const SizedBox(height: 18),
                Container(height: 1, color: _Brand.divider),
                const SizedBox(height: 18),

                // ── Price breakdown ────────────────────────────────────
                if (data.lineItems != null && data.lineItems!.isNotEmpty) ...[
                  ...data.lineItems!.map((e) => Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: _PriceRow(label: e.label, value: _fmt(e.amount)),
                  )),
                  const SizedBox(height: 10),
                  _PriceRow(label: 'Subtotal', value: _fmt(data.subtotal)),
                ] else
                  _PriceRow(label: 'Subtotal', value: _fmt(data.subtotal)),
                const SizedBox(height: 10),
                _PriceRow(label: 'Service fee', value: _fmt(data.serviceFee)),
                const SizedBox(height: 10),
                _PriceRow(label: 'Delivery fee', value: _fmt(data.deliveryFee)),
                if (data.pointsUsed > 0) ...[
                  const SizedBox(height: 10),
                  _PriceRow(
                    label: 'Points redeemed',
                    value: '${_fmtPoints(data.pointsUsed)} pts',
                  ),
                ],

                const SizedBox(height: 14),
                Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 14, vertical: 12),
                  decoration: BoxDecoration(
                    color: _Brand.amberGlow,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(
                        color: _Brand.amber.withOpacity(0.3), width: 1),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        data.pointsUsed > 0 ? 'CASH TO PAY' : 'TOTAL',
                        style: const TextStyle(
                          color: _Brand.amber,
                          fontSize: 12,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 2,
                        ),
                      ),
                      Text(
                        _fmt(data.total),
                        style: const TextStyle(
                          color: _Brand.amber,
                          fontSize: 18,
                          fontWeight: FontWeight.w800,
                          fontFamily: 'RobotoMono',
                          letterSpacing: 1,
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 20),

                // ── CTA button: COMPLETE ORDER when 100% points, else MAKE PAYMENT ──
                SizedBox(
                  height: 54,
                  child: ElevatedButton(
                    onPressed: (data.total <= 0 && onCompleteOrder != null)
                        ? onCompleteOrder
                        : onMakePayment,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _Brand.amber,
                      foregroundColor: Colors.black,
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          (data.total <= 0 && onCompleteOrder != null)
                              ? Icons.check_circle_rounded
                              : Icons.lock_rounded,
                          size: 16,
                          color: Colors.black,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          (data.total <= 0 && onCompleteOrder != null)
                              ? 'COMPLETE ORDER'
                              : 'MAKE PAYMENT',
                          style: const TextStyle(
                            fontWeight: FontWeight.w800,
                            letterSpacing: 2,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                const SizedBox(height: 12),

                // ── Security note ──────────────────────────────────────
                const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.shield_outlined,
                        size: 12, color: _Brand.textMuted),
                    SizedBox(width: 4),
                    Text(
                      'Secured & encrypted payment',
                      style: TextStyle(
                        color: _Brand.textMuted,
                        fontSize: 11,
                        letterSpacing: 0.3,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// ── Sub-widgets ───────────────────────────────────────────────────────────────

class _DetailRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  const _DetailRow(
      {required this.icon, required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 30,
          height: 30,
          decoration: BoxDecoration(
            color: _Brand.amberGlow,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(icon, color: _Brand.amber, size: 15),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(label,
                  style: const TextStyle(
                    color: _Brand.textMuted,
                    fontSize: 10,
                    letterSpacing: 1.5,
                    fontWeight: FontWeight.w600,
                  )),
              const SizedBox(height: 2),
              Text(value,
                  style: const TextStyle(
                    color: _Brand.textPrimary,
                    fontSize: 13,
                    height: 1.4,
                  )),
            ],
          ),
        ),
      ],
    );
  }
}

class _PriceRow extends StatelessWidget {
  final String label;
  final String value;
  const _PriceRow({required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label,
            style: const TextStyle(color: _Brand.textMuted, fontSize: 13)),
        Text(value,
            style: const TextStyle(
              color: _Brand.textPrimary,
              fontSize: 13,
              fontFamily: 'RobotoMono',
            )),
      ],
    );
  }
}

// ── Shared points redemption (Shop, Gas, Fuel, Rescue+) ───────────────────────

/// Reusable section: balance, quick-select chips, slider, "Redeem X pts → You pay Y UGX. Balance after Z pts."
class PointsRedeemSection extends StatelessWidget {
  const PointsRedeemSection({
    super.key,
    required this.pointsBalance,
    required this.maxRedeemable,
    required this.pointsToUse,
    required this.totalUgx,
    required this.onChanged,
  });

  final int pointsBalance;
  final int maxRedeemable;
  final int pointsToUse;
  final double totalUgx;
  final ValueChanged<int> onChanged;

  static String _fmt(int n) {
    if (n < 1000) return '$n';
    final s = n.toString();
    final buf = StringBuffer();
    for (int i = 0; i < s.length; i++) {
      if (i > 0 && (s.length - i) % 3 == 0) buf.write(',');
      buf.write(s[i]);
    }
    return buf.toString();
  }

  @override
  Widget build(BuildContext context) {
    final canRedeem = maxRedeemable >= 5000;
    final payAfterPoints = (totalUgx - pointsToUse).clamp(0.0, double.infinity);
    final balanceAfter = pointsBalance - pointsToUse;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _Brand.divider),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            'Jambo Points: ${_fmt(pointsBalance)}',
            style: const TextStyle(
              color: _Brand.textPrimary,
              fontSize: 14,
              fontWeight: FontWeight.w600,
            ),
          ),
          if (canRedeem) ...[
            const SizedBox(height: 3),
            Text(
              'You can use up to ${_fmt(maxRedeemable)} points on this order.',
              style: const TextStyle(
                color: _Brand.textMuted,
                fontSize: 12,
              ),
            ),
            const SizedBox(height: 14),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                _PointsRedeemChip(
                  label: 'None',
                  selected: pointsToUse == 0,
                  onTap: () => onChanged(0),
                ),
                if (maxRedeemable >= 5000)
                  _PointsRedeemChip(
                    label: '5,000',
                    selected: pointsToUse == 5000,
                    onTap: () => onChanged(5000.clamp(0, maxRedeemable)),
                  ),
                if (maxRedeemable >= 10000)
                  _PointsRedeemChip(
                    label: '10,000',
                    selected: pointsToUse == 10000,
                    onTap: () => onChanged(10000.clamp(0, maxRedeemable)),
                  ),
                if (maxRedeemable >= 15000)
                  _PointsRedeemChip(
                    label: '15,000',
                    selected: pointsToUse == 15000,
                    onTap: () => onChanged(15000.clamp(0, maxRedeemable)),
                  ),
                if (maxRedeemable >= 20000)
                  _PointsRedeemChip(
                    label: '20,000',
                    selected: pointsToUse == 20000,
                    onTap: () => onChanged(20000.clamp(0, maxRedeemable)),
                  ),
                if (maxRedeemable >= 25000)
                  _PointsRedeemChip(
                    label: '25,000',
                    selected: pointsToUse == 25000,
                    onTap: () => onChanged(25000.clamp(0, maxRedeemable)),
                  ),
                if (maxRedeemable > 0)
                  _PointsRedeemChip(
                    label: 'Max (${_fmt(maxRedeemable)})',
                    selected: pointsToUse == maxRedeemable,
                    onTap: () => onChanged(maxRedeemable),
                  ),
              ],
            ),
            const SizedBox(height: 2),
            SliderTheme(
              data: SliderTheme.of(context).copyWith(
                activeTrackColor: _Brand.amber,
                inactiveTrackColor: _Brand.divider,
                thumbColor: _Brand.amber,
                overlayColor: _Brand.amber.withOpacity(0.2),
              ),
              child: Slider(
                value: pointsToUse.toDouble().clamp(0.0, maxRedeemable.toDouble()),
                min: 0,
                max: maxRedeemable.toDouble(),
                divisions: maxRedeemable >= 5000
                    ? (maxRedeemable / 5000).floor().clamp(1, 20)
                    : 1,
                onChanged: (v) {
                  final step = (v / 5000).round() * 5000;
                  onChanged(step.clamp(0, maxRedeemable));
                },
              ),
            ),
            Text(
              'Redeeming: ${_fmt(pointsToUse)} pts → You pay ${_fmt(payAfterPoints.floor())} UGX. \nPoints Balance: ${_fmt(balanceAfter)} pts',
              style: const TextStyle(
                color: _Brand.amber,
                fontSize: 13,
                fontWeight: FontWeight.w600,
              ),
            ),
          ] else if (pointsBalance > 0) ...[
            const SizedBox(height: 8),
            Text(
              'Min 5,000 points to redeem.',
              style: TextStyle(
                color: _Brand.textMuted.withOpacity(0.9),
                fontSize: 12,
              ),
            ),
          ],
        ],
      ),
    );
  }
}

class _PointsRedeemChip extends StatelessWidget {
  final String label;
  final bool selected;
  final VoidCallback onTap;

  const _PointsRedeemChip({
    required this.label,
    required this.selected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return FilterChip(
      label: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          fontWeight: selected ? FontWeight.w600 : FontWeight.normal,
        ),
      ),
      selected: selected,
      onSelected: (_) => onTap(),
      selectedColor: _Brand.amber.withOpacity(0.25),
      checkmarkColor: _Brand.amber,
      side: BorderSide(
        color: selected ? _Brand.amber : _Brand.divider,
      ),
    );
  }
}