import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../api_client.dart';

// ── Brand tokens ──────────────────────────────────────────────────────────────
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);
  static const green = Color(0xFF34C759);
  static const orange = Color(0xFFFF9F0A);
  static const error = Color(0xFFFF4545);
}

// ─────────────────────────────────────────────────────────────────────────────

class OrderDetailScreen extends StatefulWidget {
  const OrderDetailScreen({
    super.key,
    required this.orderId,
    required this.onUnauthorized,
  });

  final int orderId;
  final VoidCallback onUnauthorized;

  @override
  State<OrderDetailScreen> createState() => _OrderDetailScreenState();
}

class _OrderDetailScreenState extends State<OrderDetailScreen>
    with SingleTickerProviderStateMixin {
  late Dio _dio;
  Map? _order;
  bool _loading = true;
  String? _error;
  bool _otpCopied = false;

  late final AnimationController _fadeCtrl;
  late final Animation<double> _fadeAnim;

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(() => widget.onUnauthorized());
    _fadeCtrl = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 450));
    _fadeAnim = CurvedAnimation(parent: _fadeCtrl, curve: Curves.easeOut);
    _load();
  }

  @override
  void dispose() {
    _fadeCtrl.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final r = await _dio.get('/api/orders/${widget.orderId}');
      if (!mounted) return;
      setState(() {
        _order = (r.data is Map && r.data['data'] != null)
            ? r.data['data'] as Map
            : null;
        _loading = false;
      });
      _fadeCtrl.forward(from: 0);
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) {
        widget.onUnauthorized();
      }
      if (mounted) {
        setState(() {
          _loading = false;
          _error = 'Failed to load order';
        });
        _fadeCtrl.forward(from: 0);
      }
    }
  }

  // ── Helpers (logic unchanged) ──────────────────────────────────────────────

  String _formatAmount(dynamic v) {
    if (v == null) return '—';
    final d = double.tryParse(v.toString()) ?? 0;
    final s = d.toStringAsFixed(0).split('');
    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();
  }

  int _pointsUsed(Map o) {
    final v = o['points_used'];
    if (v == null) return 0;
    return int.tryParse(v.toString()) ?? 0;
  }

  double _cashPaid(Map o) {
    final total = (double.tryParse(o['total_amount']?.toString() ?? '') ?? 0);
    final pts = _pointsUsed(o).toDouble();
    return (total - pts).clamp(0.0, double.infinity);
  }

  Map? _orderSummary(Map o) {
    final summary = o['order_summary'];
    if (summary == null || summary is! Map) return null;
    return summary;
  }

  String _fuelPricePerLiterText(Map o) {
    final m = _orderSummary(o);
    if (m == null) return '—';
    final v = m['price_per_liter'];
    if (v == null) return '—';
    return '${_formatAmount(v)} UGX';
  }

  String? _orderSummaryText(Map o) {
    final summary = o['order_summary'];
    if (summary == null || summary is! Map) return null;
    final m = summary;
    final orderType = o['order_type']?.toString() ?? '';
    if (orderType == 'gas') {
      final type = m['type']?.toString() ?? '—';
      final brand = m['brand']?.toString() ?? '—';
      final size = m['size']?.toString() ?? '—';
      return '$type · $brand · $size';
    }
    if (orderType == 'fuel') {
      final brand = m['brand']?.toString() ?? '—';
      final fuelType = m['fuel_type']?.toString() ?? '—';
      final liters = m['liters'];
      final L = liters != null
          ? (liters is num ? liters.toInt() : liters.toString())
          : '—';
      final pricePerL = m['price_per_liter'];
      final priceStr = pricePerL != null
          ? '${_formatAmount(pricePerL)} UGX/L'
          : null;
      if (priceStr != null) {
        return '$brand · $fuelType · ${L}L @ $priceStr';
      }
      return '$brand · $fuelType · ${L}L';
    }
    if (orderType == 'rescue') return m['service']?.toString() ?? '—';
    if (orderType == 'shop') {
      final n = m['items_count'];
      final count =
          n != null ? (n is num ? n.toInt() : n.toString()) : '0';
      return '$count item(s)';
    }
    return null;
  }

  String _displayStatus(String rawStatus, bool hasDriver) {
    if (rawStatus == 'delivered') return 'Completed';
    if (hasDriver) return 'On the way';
    return 'Pending';
  }

  Color _statusColor(String displayStatus) {
    switch (displayStatus) {
      case 'Completed':
        return _Brand.green;
      case 'On the way':
        return _Brand.orange;
      default:
        return _Brand.amber;
    }
  }

  IconData _statusIcon(String displayStatus) {
    switch (displayStatus) {
      case 'Completed':
        return Icons.check_circle_rounded;
      case 'On the way':
        return Icons.local_shipping_rounded;
      default:
        return Icons.hourglass_top_rounded;
    }
  }

  IconData _typeIcon(String orderType) {
    switch (orderType) {
      case 'gas':
        return Icons.propane_tank_rounded;
      case 'fuel':
        return Icons.local_gas_station_rounded;
      case 'rescue':
        return Icons.emergency_rounded;
      case 'shop':
        return Icons.shopping_bag_rounded;
      default:
        return Icons.receipt_long_rounded;
    }
  }

  // ── Build ──────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    final appBar = AppBar(
      backgroundColor: _Brand.bg,
      elevation: 0,
      scrolledUnderElevation: 0,
      leading: GestureDetector(
        onTap: () => Navigator.pop(context),
        child: Container(
          margin: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: _Brand.card,
            borderRadius: BorderRadius.circular(9),
            border: Border.all(color: _Brand.divider),
          ),
          child: const Icon(Icons.arrow_back_ios_new,
              size: 13, color: _Brand.textMuted),
        ),
      ),
      title: Text(
        _order != null ? 'ORDER #${_order!['id']}' : 'ORDER DETAIL',
        style: const TextStyle(
          fontFamily: 'RobotoMono',
          color: _Brand.textPrimary,
          fontSize: 15,
          fontWeight: FontWeight.w700,
          letterSpacing: 2,
        ),
      ),
    );

    if (_loading && _order == null) {
      return Scaffold(
        backgroundColor: _Brand.bg,
        appBar: appBar,
        body: const Center(
          child: SizedBox(
            width: 32,
            height: 32,
            child: CircularProgressIndicator(
              strokeWidth: 2.5,
              valueColor: AlwaysStoppedAnimation(_Brand.amber),
            ),
          ),
        ),
      );
    }

    if (_error != null || _order == null) {
      return Scaffold(
        backgroundColor: _Brand.bg,
        appBar: appBar,
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: _Brand.error.withOpacity(0.12),
                  shape: BoxShape.circle,
                ),
                child: const Icon(Icons.receipt_long_rounded,
                    color: _Brand.error, size: 32),
              ),
              const SizedBox(height: 16),
              Text(
                _error ?? 'Order not found',
                style: const TextStyle(color: _Brand.textPrimary, fontSize: 15),
              ),
            ],
          ),
        ),
      );
    }

    final o = _order!;
    final rawStatus = o['status']?.toString() ?? '';
    final orderType = o['order_type']?.toString() ?? '—';
    final location = o['location'];
    final addressText = location != null
        ? (location['address_name']?.toString() ??
            '${location['latitude']}, ${location['longitude']}')
        : '—';
    final driver = o['driver'];
    final displayStatus = _displayStatus(rawStatus, driver != null);
    final statusColor = _statusColor(displayStatus);
    final otp = o['otp_code']?.toString();
    final summaryText = _orderSummaryText(o);
    final createdAt = o['created_at']?.toString();

    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: appBar,
      body: FadeTransition(
        opacity: _fadeAnim,
        child: SingleChildScrollView(
          padding: const EdgeInsets.fromLTRB(20, 8, 20, 40),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // ── Status hero ───────────────────────────────────────────
              _StatusHero(
                displayStatus: displayStatus,
                statusColor: statusColor,
                icon: _statusIcon(displayStatus),
                orderId: o['id']?.toString() ?? '—',
                createdAt: createdAt,
              ),

              const SizedBox(height: 20),

              // ── OTP card (high priority — shown near top) ─────────────
              if (otp != null && otp.isNotEmpty) ...[
                _OtpCard(
                  otp: otp,
                  copied: _otpCopied,
                  onCopy: () {
                    Clipboard.setData(ClipboardData(text: otp));
                    setState(() => _otpCopied = true);
                    Future.delayed(const Duration(seconds: 2),
                        () => mounted ? setState(() => _otpCopied = false) : null);
                  },
                ),
                const SizedBox(height: 20),
              ],

              // ── Info grid ─────────────────────────────────────────────
              _SectionLabel('ORDER DETAILS'),
              const SizedBox(height: 12),

              _InfoCard(children: [
                _InfoRow(
                  icon: _typeIcon(orderType),
                  label: 'Service type',
                  value: orderType.toUpperCase(),
                  valueColor: _Brand.amber,
                ),
                if (summaryText != null) ...[
                  const _RowDivider(),
                  _InfoRow(
                    icon: Icons.inventory_2_rounded,
                    label: 'What you ordered',
                    value: summaryText,
                  ),
                ],
                if (orderType == 'fuel' && _orderSummary(o) != null) ...[
                  const _RowDivider(),
                  _InfoRow(
                    icon: Icons.local_gas_station_rounded,
                    label: 'Fuel type',
                    value: _orderSummary(o)!['fuel_type']?.toString() ?? '—',
                  ),
                  const _RowDivider(),
                  _InfoRow(
                    icon: Icons.attach_money_rounded,
                    label: 'Price per liter',
                    value: _fuelPricePerLiterText(o),
                    valueColor: _Brand.amber,
                    valueMono: true,
                  ),
                ],
                const _RowDivider(),
                _InfoRow(
                  icon: Icons.location_on_rounded,
                  label: 'Delivery address',
                  value: addressText,
                ),
                const _RowDivider(),
                if (_pointsUsed(o) > 0) ...[
                  _InfoRow(
                    icon: Icons.stars_rounded,
                    label: 'Points redeemed',
                    value: '${_formatAmount(o['points_used'])} pts',
                    valueColor: _Brand.amber,
                    valueMono: true,
                  ),
                  const _RowDivider(),
                  _InfoRow(
                    icon: Icons.payments_rounded,
                    label: 'Cash paid',
                    value: '${_formatAmount(_cashPaid(o))} UGX',
                    valueColor: _Brand.amber,
                    valueMono: true,
                  ),
                ] else
                  _InfoRow(
                    icon: Icons.payments_rounded,
                    label: 'Total amount',
                    value: '${_formatAmount(o['total_amount'])} UGX',
                    valueColor: _Brand.amber,
                    valueMono: true,
                  ),
                if (createdAt != null) ...[
                  const _RowDivider(),
                  _InfoRow(
                    icon: Icons.calendar_today_rounded,
                    label: 'Date',
                    value: _formatDate(createdAt),
                  ),
                ],
              ]),

              // ── Driver section ────────────────────────────────────────
              if (driver != null) ...[
                const SizedBox(height: 20),
                _SectionLabel('YOUR DRIVER'),
                const SizedBox(height: 12),
                _DriverCard(
                  driver: driver,
                  showCallButton: rawStatus != 'delivered',
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  String _formatDate(String raw) {
    try {
      final dt = DateTime.parse(raw).toLocal();
      final months = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
      ];
      final h = dt.hour.toString().padLeft(2, '0');
      final m = dt.minute.toString().padLeft(2, '0');
      return '${dt.day} ${months[dt.month - 1]} ${dt.year}  $h:$m';
    } catch (_) {
      return raw;
    }
  }
}

// ── Status hero ───────────────────────────────────────────────────────────────

class _StatusHero extends StatelessWidget {
  final String displayStatus;
  final Color statusColor;
  final IconData icon;
  final String orderId;
  final String? createdAt;

  const _StatusHero({
    required this.displayStatus,
    required this.statusColor,
    required this.icon,
    required this.orderId,
    this.createdAt,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF1E2430), Color(0xFF191D25)],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: statusColor.withOpacity(0.25), width: 1.5),
        boxShadow: [
          BoxShadow(
            color: statusColor.withOpacity(0.08),
            blurRadius: 20,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 56,
            height: 56,
            decoration: BoxDecoration(
              color: statusColor.withOpacity(0.15),
              shape: BoxShape.circle,
              border: Border.all(color: statusColor.withOpacity(0.35), width: 1.5),
            ),
            child: Icon(icon, color: statusColor, size: 26),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: statusColor.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(5),
                    border: Border.all(
                        color: statusColor.withOpacity(0.4), width: 1),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        width: 5,
                        height: 5,
                        decoration: BoxDecoration(
                            color: statusColor, shape: BoxShape.circle),
                      ),
                      const SizedBox(width: 5),
                      Text(
                        displayStatus.toUpperCase(),
                        style: TextStyle(
                          color: statusColor,
                          fontSize: 9,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 1.2,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 6),
                const Text(
                  'Order status',
                  style: TextStyle(
                    color: _Brand.textMuted,
                    fontSize: 11,
                    letterSpacing: 0.3,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// ── OTP card ──────────────────────────────────────────────────────────────────

class _OtpCard extends StatelessWidget {
  final String otp;
  final bool copied;
  final VoidCallback onCopy;
  const _OtpCard(
      {required this.otp, required this.copied, required this.onCopy});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: _Brand.amberGlow,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _Brand.amber.withOpacity(0.4), width: 1.5),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Row(
              children: [
                Icon(Icons.lock_rounded, color: _Brand.amber, size: 15),
                SizedBox(width: 6),
                Text(
                  'DELIVERY OTP',
                  style: TextStyle(
                    color: _Brand.amber,
                    fontSize: 10,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 2,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            const Text(
              'Share this code with your driver to confirm delivery',
              style: TextStyle(color: _Brand.textMuted, fontSize: 12, height: 1.4),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: Text(
                    otp,
                    style: const TextStyle(
                      color: _Brand.textPrimary,
                      fontFamily: 'RobotoMono',
                      fontSize: 36,
                      fontWeight: FontWeight.w800,
                      letterSpacing: 10,
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: onCopy,
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 14, vertical: 9),
                    decoration: BoxDecoration(
                      color: copied
                          ? _Brand.green.withOpacity(0.15)
                          : _Brand.card,
                      borderRadius: BorderRadius.circular(9),
                      border: Border.all(
                        color: copied
                            ? _Brand.green.withOpacity(0.5)
                            : _Brand.divider,
                        width: 1,
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          copied
                              ? Icons.check_rounded
                              : Icons.copy_rounded,
                          color: copied ? _Brand.green : _Brand.textMuted,
                          size: 14,
                        ),
                        const SizedBox(width: 5),
                        Text(
                          copied ? 'Copied' : 'Copy',
                          style: TextStyle(
                            color:
                                copied ? _Brand.green : _Brand.textMuted,
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

// ── Info card ─────────────────────────────────────────────────────────────────

class _InfoCard extends StatelessWidget {
  final List<Widget> children;
  const _InfoCard({required this.children});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _Brand.divider),
      ),
      child: Column(children: children),
    );
  }
}

class _InfoRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  final Color? valueColor;
  final bool valueMono;

  const _InfoRow({
    required this.icon,
    required this.label,
    required this.value,
    this.valueColor,
    this.valueMono = false,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 32,
            height: 32,
            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: 3),
                Text(
                  value,
                  style: TextStyle(
                    color: valueColor ?? _Brand.textPrimary,
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    fontFamily: valueMono ? 'RobotoMono' : null,
                    letterSpacing: valueMono ? 0.5 : null,
                    height: 1.4,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _RowDivider extends StatelessWidget {
  const _RowDivider();

  @override
  Widget build(BuildContext context) => const Padding(
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Divider(color: _Brand.divider, height: 1),
      );
}

// ── Driver card ───────────────────────────────────────────────────────────────

class _DriverCard extends StatelessWidget {
  final Map driver;
  final bool showCallButton;

  const _DriverCard({required this.driver, this.showCallButton = true});

  @override
  Widget build(BuildContext context) {
    final name =
        (driver['name'] ?? driver['phone'] ?? '—').toString();
    final phone = driver['phone']?.toString();

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _Brand.divider),
      ),
      child: Row(
        children: [
          Container(
            width: 44,
            height: 44,
            decoration: BoxDecoration(
              color: _Brand.amberGlow,
              shape: BoxShape.circle,
              border: Border.all(
                  color: _Brand.amber.withOpacity(0.3), width: 1.5),
            ),
            child: const Icon(Icons.person_rounded,
                color: _Brand.amber, size: 22),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('DRIVER',
                    style: TextStyle(
                      color: _Brand.textMuted,
                      fontSize: 10,
                      letterSpacing: 1.5,
                      fontWeight: FontWeight.w600,
                    )),
                const SizedBox(height: 2),
                Text(name,
                    style: const TextStyle(
                      color: _Brand.textPrimary,
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                    )),
              ],
            ),
          ),
          if (showCallButton && phone != null)
            GestureDetector(
              onTap: () async {
                final uri = Uri(scheme: 'tel', path: phone);
                if (await canLaunchUrl(uri)) await launchUrl(uri);
              },
              child: Container(
                padding: const EdgeInsets.symmetric(
                    horizontal: 14, vertical: 9),
                decoration: BoxDecoration(
                  color: _Brand.amberGlow,
                  borderRadius: BorderRadius.circular(9),
                  border: Border.all(
                      color: _Brand.amber.withOpacity(0.4), width: 1),
                ),
                child: const Row(
                  children: [
                    Icon(Icons.phone_rounded, color: _Brand.amber, size: 14),
                    SizedBox(width: 5),
                    Text('Call',
                        style: TextStyle(
                          color: _Brand.amber,
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                        )),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}

// ── Shared widgets ────────────────────────────────────────────────────────────

class _SectionLabel extends StatelessWidget {
  final String text;
  const _SectionLabel(this.text);

  @override
  Widget build(BuildContext context) => Text(
        text,
        style: const TextStyle(
          color: _Brand.textMuted,
          fontSize: 10,
          letterSpacing: 2.5,
          fontWeight: FontWeight.w600,
        ),
      );
}