import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../api_client.dart';
import '../widgets/banner_ad_widget.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 error = Color(0xFFFF4545);
}

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

class HomeScreen extends StatefulWidget {
  const HomeScreen({
    super.key,
    required this.onUnauthorized,
    this.refreshTrigger,
    this.orderCountRefreshTrigger,
  });
  final VoidCallback onUnauthorized;
  /// When this notifier's value changes, the screen will reload (e.g. to show new active order).
  final ValueNotifier<int>? refreshTrigger;
  /// When home data is loaded/refreshed, increment this so the app bar order badge can update.
  final ValueNotifier<int>? orderCountRefreshTrigger;

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  late Dio _dio;
  Map? _config;
  Map? _activeOrder;
  Map? _user;
  List<dynamic> _lastOrders = [];
  bool _loading = true;
  String? _error;

  late final AnimationController _fadeCtrl;
  late final Animation<double> _fadeAnim;
  ValueNotifier<int>? _refreshTrigger;

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

  void _onRefreshTriggered() {
    if (mounted) _load();
  }

  @override
  void dispose() {
    _refreshTrigger?.removeListener(_onRefreshTriggered);
    _fadeCtrl.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final r = await Future.wait([
        _dio.get('/api/auth/me'),
        _dio.get('/api/config'),
        _dio.get('/api/orders/active'),
        _dio.get('/api/orders?limit=5'),
      ]);
      if (!mounted) return;
      setState(() {
        _user = (r[0].data is Map && r[0].data['data'] != null)
            ? r[0].data['data'] as Map
            : null;
        _config = (r[1].data is Map && r[1].data['data'] != null)
            ? r[1].data['data'] as Map
            : null;
        _activeOrder = (r[2].data is Map && r[2].data['data'] != null)
            ? r[2].data['data'] as Map?
            : null;
        _lastOrders = (r[3].data is Map && r[3].data['data'] is List)
            ? List.from(r[3].data['data'] as List)
            : [];
        _loading = false;
      });
      widget.orderCountRefreshTrigger?.value++;
      _fadeCtrl.forward(from: 0);
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) {
        widget.onUnauthorized();
        return;
      }
      if (mounted) {
        setState(() {
          _loading = false;
          _error = 'Failed to load';
        });
        _fadeCtrl.forward(from: 0);
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    if (_loading && _user == null) {
      return const Center(
        child: SizedBox(
          width: 32,
          height: 32,
          child: CircularProgressIndicator(
            strokeWidth: 2.5,
            valueColor: AlwaysStoppedAnimation(_Brand.amber),
          ),
        ),
      );
    }

    final phone = _user?['phone']?.toString() ?? '';
    final greeting = _greeting();

    return RefreshIndicator(
      onRefresh: _load,
      color: _Brand.amber,
      backgroundColor: _Brand.card,
      child: FadeTransition(
        opacity: _fadeAnim,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(20, 4, 20, 40),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const SizedBox(height: 8),

              // ── Greeting header ────────────────────────────────────────
              _GreetingHeader(greeting: greeting, phone: phone),
              const SizedBox(height: 20),

              // ── Error ──────────────────────────────────────────────────
              if (_error != null) ...[
                _ErrorBanner(_error!),
                const SizedBox(height: 16),
              ],

              // ── Banner ad ──────────────────────────────────────────────
              const BannerAdWidget(),
              const SizedBox(height: 16),

              // ── Points balance card ─────────────────────────────────────
              _PointsBalanceCard(
                pointsBalance: (_user != null && _user!['points_balance'] != null)
                    ? (int.tryParse(_user!['points_balance'].toString()) ?? 0)
                    : 0,
              ),
              const SizedBox(height: 24),

              // ── Active order ───────────────────────────────────────────
              if (_activeOrder != null && _activeOrder!['id'] != null) ...[
                _ActiveOrderCard(order: _activeOrder!),
                const SizedBox(height: 24),
              ],

              // ── Recent orders ──────────────────────────────────────────
              if (_lastOrders.isNotEmpty) ...[
                _SectionLabel('RECENT ORDERS'),
                const SizedBox(height: 12),
                ..._lastOrders.take(5).map((o) {
                  final m = o is Map ? o : {};
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 8),
                    child: _OrderRow(order: m),
                  );
                }),
              ],

              if (_lastOrders.isEmpty && _activeOrder == null) ...[
                const SizedBox(height: 40),
                _EmptyState(),
              ],
            ],
          ),
        ),
      ),
    );
  }

  String _greeting() {
    final hour = DateTime.now().hour;
    if (hour < 12) return 'Good morning';
    if (hour < 17) return 'Good afternoon';
    return 'Good evening';
  }
}

// ── Greeting header ───────────────────────────────────────────────────────────

class _GreetingHeader extends StatelessWidget {
  final String greeting;
  final String phone;
  const _GreetingHeader({required this.greeting, required this.phone});

  @override
  Widget build(BuildContext context) {
    // Format phone for display: +256 7XX XXX XXX
    final display = phone.isNotEmpty
        ? (phone.startsWith('256')
            ? '+${phone.substring(0, 3)} ${phone.substring(3)}'
            : phone)
        : '';

    return Row(
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                greeting,
                style: const TextStyle(
                  color: _Brand.textMuted,
                  fontSize: 13,
                  letterSpacing: 0.3,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                display.isNotEmpty ? display : 'Welcome back',
                style: const TextStyle(
                  color: _Brand.textPrimary,
                  fontSize: 20,
                  fontWeight: FontWeight.w700,
                  fontFamily: 'RobotoMono',
                  letterSpacing: 1,
                ),
              ),
            ],
          ),
        ),
        // Avatar badge
        Container(
          width: 44,
          height: 44,
          decoration: BoxDecoration(
            color: _Brand.amberGlow,
            shape: BoxShape.circle,
            border: Border.all(
                color: _Brand.amber.withOpacity(0.4), width: 1.5),
          ),
          child: const Icon(Icons.person_rounded,
              color: _Brand.amber, size: 22),
        ),
      ],
    );
  }
}

// ── Points balance card ──────────────────────────────────────────────────────

class _PointsBalanceCard extends StatelessWidget {
  final int pointsBalance;
  const _PointsBalanceCard({required this.pointsBalance});

  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) {
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _Brand.divider),
        boxShadow: [
          BoxShadow(
            color: _Brand.amberGlow,
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: _Brand.amberGlow,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.stars_rounded,
                    color: _Brand.amber, size: 22),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'JAMBO POINTS',
                      style: TextStyle(
                        color: _Brand.textMuted,
                        fontSize: 10,
                        fontWeight: FontWeight.w700,
                        letterSpacing: 1.5,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      _fmt(pointsBalance),
                      style: const TextStyle(
                        color: _Brand.amber,
                        fontSize: 22,
                        fontWeight: FontWeight.w800,
                        fontFamily: 'RobotoMono',
                        letterSpacing: 1,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            '10,000 UGX spent = 10 points • Min 5,000 to redeem',
            style: TextStyle(
              color: _Brand.textMuted.withOpacity(0.9),
              fontSize: 11,
              height: 1.3,
            ),
          ),
        ],
      ),
    );
  }
}

// ── Active order card ─────────────────────────────────────────────────────────

class _ActiveOrderCard extends StatelessWidget {
  final Map order;
  const _ActiveOrderCard({required this.order});

  @override
  Widget build(BuildContext context) {
    final driver = order['driver'];
    final location = order['location'];
    final driverPhone =
        driver != null ? driver['phone'] as String? : null;
    final driverName = driver != null
        ? (driver['name'] ?? driver['phone'] ?? '—').toString()
        : '—';
    final lat =
        location != null ? (location['latitude'] as num?)?.toDouble() : null;
    final lng =
        location != null ? (location['longitude'] as num?)?.toDouble() : null;

    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF1E2430), Color(0xFF191D25)],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _Brand.amber.withOpacity(0.25), width: 1.5),
        boxShadow: [
          BoxShadow(
            color: _Brand.amber.withOpacity(0.08),
            blurRadius: 20,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(18),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Status badge
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _Brand.green.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(
                        color: _Brand.green.withOpacity(0.4), width: 1),
                  ),
                  child: Row(
                    children: [
                      Container(
                        width: 6,
                        height: 6,
                        decoration: const BoxDecoration(
                            color: _Brand.green, shape: BoxShape.circle),
                      ),
                      const SizedBox(width: 5),
                      const Text('ACTIVE ORDER',
                          style: TextStyle(
                            color: _Brand.green,
                            fontSize: 10,
                            fontWeight: FontWeight.w700,
                            letterSpacing: 1,
                          )),
                    ],
                  ),
                ),
                const Spacer(),
                const Icon(Icons.local_shipping_rounded,
                    color: _Brand.amber, size: 20),
              ],
            ),

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

            // Driver info row
            if (driver != null) ...[
              Row(
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    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: 20),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('YOUR DRIVER',
                            style: TextStyle(
                              color: _Brand.textMuted,
                              fontSize: 10,
                              letterSpacing: 1.5,
                            )),
                        const SizedBox(height: 2),
                        Text(driverName,
                            style: const TextStyle(
                              color: _Brand.textPrimary,
                              fontSize: 15,
                              fontWeight: FontWeight.w600,
                            )),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 14),

              // Action buttons
              Row(
                children: [
                  if (driverPhone != null)
                    Expanded(
                      child: _ActionBtn(
                        label: 'Call Driver',
                        icon: Icons.phone_rounded,
                        onTap: () async {
                          final uri =
                              Uri(scheme: 'tel', path: driverPhone);
                          if (await canLaunchUrl(uri)) {
                            await launchUrl(uri);
                          }
                        },
                      ),
                    ),
                  if (driverPhone != null && lat != null && lng != null)
                    const SizedBox(width: 10),
                  if (lat != null && lng != null)
                    Expanded(
                      child: _ActionBtn(
                        label: 'Open Maps',
                        icon: Icons.map_rounded,
                        onTap: () async {
                          final uri = Uri.parse(
                              'https://www.google.com/maps?q=$lat,$lng');
                          if (await canLaunchUrl(uri)) {
                            await launchUrl(uri,
                                mode: LaunchMode.externalApplication);
                          }
                        },
                      ),
                    ),
                ],
              ),
            ] else
              const Text('Awaiting driver assignment…',
                  style:
                      TextStyle(color: _Brand.textMuted, fontSize: 13)),
          ],
        ),
      ),
    );
  }
}

class _ActionBtn extends StatelessWidget {
  final String label;
  final IconData icon;
  final VoidCallback onTap;
  const _ActionBtn(
      {required this.label, required this.icon, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding:
            const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
        decoration: BoxDecoration(
          color: _Brand.amberGlow,
          borderRadius: BorderRadius.circular(9),
          border:
              Border.all(color: _Brand.amber.withOpacity(0.4), width: 1),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: _Brand.amber, size: 14),
            const SizedBox(width: 6),
            Text(label,
                style: const TextStyle(
                  color: _Brand.amber,
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                )),
          ],
        ),
      ),
    );
  }
}

// ── Order row ─────────────────────────────────────────────────────────────────

class _OrderRow extends StatelessWidget {
  final Map order;
  const _OrderRow({required this.order});

  Color _statusColor(String status) {
    final s = status.toLowerCase();
    if (s == 'delivered' || s == 'completed') return _Brand.green;
    if (s == 'cancelled' || s == 'failed') return _Brand.error;
    return _Brand.amber;
  }

  IconData _statusIcon(String status) {
    final s = status.toLowerCase();
    if (s == 'delivered' || s == 'completed') {
      return Icons.check_circle_rounded;
    }
    if (s == 'cancelled' || s == 'failed') return Icons.cancel_rounded;
    return Icons.local_shipping_rounded;
  }

  String _fmt(dynamic v) {
    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();
  }

  @override
  Widget build(BuildContext context) {
    final id = order['id']?.toString() ?? '—';
    final status = order['status']?.toString() ?? 'pending';
    final amount = order['total_amount'];
    final color = _statusColor(status);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _Brand.divider),
      ),
      child: Row(
        children: [
          // Status icon
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: color.withOpacity(0.12),
              borderRadius: BorderRadius.circular(9),
            ),
            child: Icon(_statusIcon(status), color: color, size: 18),
          ),
          const SizedBox(width: 12),

          // Order info
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Order #$id',
                    style: const TextStyle(
                      color: _Brand.textPrimary,
                      fontSize: 13,
                      fontWeight: FontWeight.w600,
                    )),
                const SizedBox(height: 2),
                Text(
                  status.toUpperCase(),
                  style: TextStyle(
                    color: color,
                    fontSize: 10,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 1,
                  ),
                ),
              ],
            ),
          ),

          // Amount
          if (amount != null)
            Text(
              '${_fmt(amount)} UGX',
              style: const TextStyle(
                color: _Brand.amber,
                fontSize: 13,
                fontFamily: 'RobotoMono',
                fontWeight: FontWeight.w700,
              ),
            ),
        ],
      ),
    );
  }
}

// ── Empty state ───────────────────────────────────────────────────────────────

class _EmptyState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Container(
            width: 72,
            height: 72,
            decoration: BoxDecoration(
              color: _Brand.amberGlow,
              shape: BoxShape.circle,
              border: Border.all(
                  color: _Brand.amber.withOpacity(0.3), width: 1.5),
            ),
            child: const Icon(Icons.local_gas_station_rounded,
                color: _Brand.amber, size: 34),
          ),
          const SizedBox(height: 16),
          const Text('No orders yet',
              style: TextStyle(
                  color: _Brand.textPrimary,
                  fontSize: 16,
                  fontWeight: FontWeight.w600)),
          const SizedBox(height: 6),
          const Text('Your order history will appear here',
              style: TextStyle(color: _Brand.textMuted, fontSize: 13)),
        ],
      ),
    );
  }
}

// ── 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,
        ),
      );
}

class _ErrorBanner extends StatelessWidget {
  final String message;
  const _ErrorBanner(this.message);

  @override
  Widget build(BuildContext context) => Container(
        padding:
            const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
        decoration: BoxDecoration(
          color: _Brand.error.withOpacity(0.12),
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: _Brand.error.withOpacity(0.4)),
        ),
        child: Row(
          children: [
            const Icon(Icons.warning_amber_rounded,
                color: _Brand.error, size: 18),
            const SizedBox(width: 10),
            Expanded(
              child: Text(message,
                  style: const TextStyle(
                      color: _Brand.error, fontSize: 13, height: 1.4)),
            ),
          ],
        ),
      );
}