import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api_client.dart';
import '../widgets/banner_ad_widget.dart';
import 'order_detail_screen.dart';

// ── Design tokens (design.json) ───────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  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 red = Color(0xFFFF4545);
  static const screenPadding = 20.0;
  static const cardRadius = 16.0;
}

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

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

  final VoidCallback onUnauthorized;

  @override
  State<OrdersListScreen> createState() => _OrdersListScreenState();
}

class _OrdersListScreenState extends State<OrdersListScreen> {
  late Dio _dio;
  List<dynamic> _orders = [];
  bool _loading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(() => widget.onUnauthorized());
    _load();
  }

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

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: AppBar(
        backgroundColor: _Brand.surface,
        elevation: 0,
        title: const Text(
          'MY ORDERS',
          style: TextStyle(
            fontFamily: 'RobotoMono',
            fontSize: 15,
            fontWeight: FontWeight.w700,
            letterSpacing: 3,
            color: _Brand.textPrimary,
          ),
        ),
        leading: Padding(
          padding: const EdgeInsets.only(left: 12),
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              padding: 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),
            ),
          ),
        ),
        leadingWidth: 56,
      ),
      body: Column(
        children: [
          const BannerAdWidget(),
          Expanded(
            child: _loading
                ? const Center(
                    child: SizedBox(
                      width: 32,
                      height: 32,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.5,
                        valueColor: AlwaysStoppedAnimation(_Brand.amber),
                      ),
                    ),
                  )
                : _error != null
                    ? Center(
                        child: Text(
                          _error!,
                          style: const TextStyle(color: _Brand.red, fontSize: 14),
                        ),
                      )
                    : _orders.isEmpty
                        ? Center(
                            child: Text(
                              'No orders yet',
                              style: TextStyle(color: _Brand.textMuted, fontSize: 15),
                            ),
                          )
                        : RefreshIndicator(
                            onRefresh: _load,
                            color: _Brand.amber,
                            backgroundColor: _Brand.card,
                            child: ListView.builder(
                              padding: const EdgeInsets.fromLTRB(_Brand.screenPadding, 12, _Brand.screenPadding, 40),
                              itemCount: _orders.length,
                              itemBuilder: (context, i) {
                                final o = _orders[i] as Map;
                                final status = o['status']?.toString() ?? '';
                                final total = o['total_amount'];
                                final orderType = o['order_type']?.toString() ?? '—';
                                return Padding(
                                  padding: const EdgeInsets.only(bottom: 12),
                                  child: _OrderCard(
                                    order: o,
                                    orderType: orderType,
                                    status: status,
                                    total: total,
                                    onTap: () => Navigator.of(context).push(
                                      MaterialPageRoute(
                                        builder: (_) => OrderDetailScreen(
                                          orderId: o['id'],
                                          onUnauthorized: widget.onUnauthorized,
                                        ),
                                      ),
                                    ).then((_) => _load()),
                                  ),
                                );
                              },
                            ),
                          ),
          ),
        ],
      ),
    );
  }
}

// ── Order card with status chip (design.json card + status_badge) ──────────────
class _OrderCard extends StatelessWidget {
  final Map order;
  final String orderType;
  final String status;
  final dynamic total;
  final VoidCallback onTap;

  const _OrderCard({
    required this.order,
    required this.orderType,
    required this.status,
    required this.total,
    required this.onTap,
  });

  static Color _statusColor(String status) {
    final s = status.toLowerCase().replaceAll(RegExp(r'[\s_-]'), '');
    if (s.contains('complete') || s.contains('delivered')) return _Brand.green;
    if (s.contains('way') || s.contains('ontheway') || s.contains('delivering')) return _Brand.orange;
    if (s.contains('cancel') || s.contains('fail')) return _Brand.red;
    return _Brand.amber; // Pending / default
  }

  static String _statusLabel(String status) {
    if (status.isEmpty) return 'PENDING';
    final s = status.toLowerCase().replaceAll(RegExp(r'[\s_-]'), '');
    if (s.contains('complete') || s.contains('delivered')) return 'DELIVERED';
    if (s.contains('way') || s.contains('ontheway') || s.contains('delivering')) return 'ON THE WAY';
    if (s.contains('cancel') || s.contains('fail')) return 'CANCELLED';
    return status.toUpperCase();
  }

  String _formatAmount(dynamic v) {
    if (v == null) return '—';
    if (v is num) return v.toStringAsFixed(0);
    return v.toString();
  }

  IconData _iconForType(String type) {
    switch (type) {
      case 'gas': return Icons.propane_tank_rounded;
      case 'fuel': return Icons.local_gas_station_rounded;
      case 'shop': return Icons.shopping_cart_rounded;
      case 'rescue': return Icons.emergency_rounded;
      default: return Icons.receipt_long_rounded;
    }
  }

  @override
  Widget build(BuildContext context) {
    final statusColor = _statusColor(status);
    final statusLabel = _statusLabel(status);

    return Material(
      color: _Brand.card,
      borderRadius: BorderRadius.circular(_Brand.cardRadius),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(_Brand.cardRadius),
        child: Container(
          padding: const EdgeInsets.all(18),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(_Brand.cardRadius),
            border: Border.all(color: _Brand.divider),
          ),
          child: Row(
            children: [
              Container(
                width: 44,
                height: 44,
                decoration: BoxDecoration(
                  color: _Brand.amberGlow,
                  borderRadius: BorderRadius.circular(9),
                  border: Border.all(color: _Brand.amber.withOpacity(0.35)),
                ),
                child: Icon(_iconForType(orderType), size: 22, color: _Brand.amber),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Order #${order['id']}',
                      style: const TextStyle(
                        color: _Brand.textPrimary,
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    const SizedBox(height: 6),
                    _StatusChip(label: statusLabel, color: statusColor),
                    const SizedBox(height: 8),
                    Text(
                      '${_formatAmount(total)} UGX',
                      style: const TextStyle(
                        fontFamily: 'RobotoMono',
                        color: _Brand.amber,
                        fontSize: 13,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(Icons.chevron_right_rounded, color: _Brand.textMuted, size: 22),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Status chip (design.json status_badge) ────────────────────────────────────
class _StatusChip extends StatelessWidget {
  final String label;
  final Color color;

  const _StatusChip({required this.label, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.15),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: color.withOpacity(0.4)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 6,
            height: 6,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 5),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 10,
              fontWeight: FontWeight.w700,
              letterSpacing: 1,
            ),
          ),
        ],
      ),
    );
  }
}
