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';
import '../auth_storage.dart';

// ── Brand tokens (shared design system) ──────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const cardElevated = Color(0xFF272B34);
  static const amber = Color(0xFFFF9500);
  static const amberDark = Color(0xFFCC7700);
  static const amberGlow = Color(0x33FF9500);
  static const amberGlowStrong = Color(0x55FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const error = Color(0xFFFF4545);
  static const divider = Color(0xFF2C3040);
  static const green = Color(0xFF34C759);
  static const blue = Color(0xFF0A84FF);
}

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

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({super.key});

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen>
    with TickerProviderStateMixin {
  late Dio _dio;
  Map? _config;
  Map? _activeOrder;
  bool _loading = true;
  String? _error;

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

  // Ticker scroll
  final ScrollController _tickerScroll = ScrollController();

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

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

  void _onUnauthorized() {
    AuthStorage.clearToken();
    if (mounted) {
      Navigator.of(context).pushNamedAndRemoveUntil('/login', (r) => false);
    }
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final results = await Future.wait([
        _dio.get('/api/config'),
        _dio.get('/api/orders/active'),
      ]);
      final configData = results[0].data;
      final orderData = results[1].data;
      if (mounted) {
        setState(() {
          _config = configData is Map ? configData['data'] as Map? : null;
          _activeOrder = orderData is Map ? orderData['data'] as Map? : null;
          _loading = false;
        });
        _fadeCtrl.forward(from: 0);
      }
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) {
        _onUnauthorized();
        return;
      }
      if (mounted) {
        setState(() {
          _loading = false;
          _error = 'Failed to load dashboard';
        });
        _fadeCtrl.forward(from: 0);
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));

    if (_loading && _config == null) {
      return const Scaffold(
        backgroundColor: _Brand.bg,
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 36,
                height: 36,
                child: CircularProgressIndicator(
                  strokeWidth: 2.5,
                  valueColor: AlwaysStoppedAnimation(_Brand.amber),
                ),
              ),
              SizedBox(height: 16),
              Text('Loading…',
                  style: TextStyle(color: _Brand.textMuted, fontSize: 13)),
            ],
          ),
        ),
      );
    }

    final ticker = _config != null && _config!['ticker'] != null
        ? List.from(_config!['ticker'] as List)
        : <dynamic>[];

    return Scaffold(
      backgroundColor: _Brand.bg,
      body: FadeTransition(
        opacity: _fadeAnim,
        child: RefreshIndicator(
          onRefresh: _load,
          color: _Brand.amber,
          backgroundColor: _Brand.card,
          child: CustomScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            slivers: [
              // ── Sliver App Bar ─────────────────────────────────────────
              SliverAppBar(
                backgroundColor: _Brand.surface,
                surfaceTintColor: Colors.transparent,
                expandedHeight: 120,
                pinned: true,
                flexibleSpace: FlexibleSpaceBar(
                  titlePadding:
                      const EdgeInsets.only(left: 20, bottom: 14),
                  title: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: 28,
                        height: 28,
                        decoration: BoxDecoration(
                          color: _Brand.amberGlow,
                          borderRadius: BorderRadius.circular(7),
                          border: Border.all(
                              color: _Brand.amber.withOpacity(0.4),
                              width: 1),
                        ),
                        child: const Icon(Icons.water_drop_rounded,
                            color: _Brand.amber, size: 14),
                      ),
                      const SizedBox(width: 8),
                      const Text(
                        'JAMBO',
                        style: TextStyle(
                          fontFamily: 'RobotoMono',
                          color: _Brand.textPrimary,
                          fontSize: 18,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 4,
                        ),
                      ),
                    ],
                  ),
                  background: Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [Color(0xFF1C2028), _Brand.surface],
                      ),
                    ),
                    child: Align(
                      alignment: Alignment.topRight,
                      child: Opacity(
                        opacity: 0.06,
                        child: Icon(Icons.local_gas_station,
                            size: 140, color: _Brand.amber),
                      ),
                    ),
                  ),
                ),
                actions: [
                  IconButton(
                    icon: Container(
                      padding: const EdgeInsets.all(6),
                      decoration: BoxDecoration(
                        color: _Brand.card,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: _Brand.divider),
                      ),
                      child: const Icon(Icons.logout_rounded,
                          size: 16, color: _Brand.textMuted),
                    ),
                    onPressed: () async {
                      await AuthStorage.clearToken();
                      if (mounted) {
                        Navigator.of(context).pushNamedAndRemoveUntil(
                            '/login', (r) => false);
                      }
                    },
                  ),
                  const SizedBox(width: 8),
                ],
              ),

              // ── Body ───────────────────────────────────────────────────
              SliverPadding(
                padding: const EdgeInsets.all(20),
                sliver: SliverList(
                  delegate: SliverChildListDelegate([
                    // Error
                    if (_error != null) ...[
                      _ErrorBanner(_error!),
                      const SizedBox(height: 20),
                    ],

                    // Ticker
                    if (ticker.isNotEmpty) ...[
                      _TickerStrip(ticker: ticker),
                      const SizedBox(height: 24),
                    ],

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

                    // Section label
                    _SectionLabel('QUICK ACTIONS'),
                    const SizedBox(height: 14),

                    // Action grid
                    _ActionGrid(),

                    const SizedBox(height: 32),
                  ]),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Ticker strip ──────────────────────────────────────────────────────────────

class _TickerStrip extends StatelessWidget {
  final List<dynamic> ticker;
  const _TickerStrip({required this.ticker});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 44,
      decoration: BoxDecoration(
        color: _Brand.card,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: _Brand.divider),
      ),
      child: Row(
        children: [
          // Label badge
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            decoration: const BoxDecoration(
              color: _Brand.amberGlow,
              borderRadius:
                  BorderRadius.horizontal(left: Radius.circular(9)),
              border: Border(
                  right: BorderSide(color: _Brand.amber, width: 1)),
            ),
            child: const Row(
              children: [
                Icon(Icons.show_chart_rounded, color: _Brand.amber, size: 13),
                SizedBox(width: 4),
                Text('LIVE',
                    style: TextStyle(
                      color: _Brand.amber,
                      fontSize: 10,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 1.5,
                    )),
              ],
            ),
          ),
          // Scrollable prices
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Row(
                children: ticker.map<Widget>((e) {
                  final m = e is Map ? e : {};
                  return Padding(
                    padding: const EdgeInsets.only(right: 20),
                    child: Row(
                      children: [
                        Text(
                          '${m['provider'] ?? ''} ${m['item'] ?? ''}',
                          style: const TextStyle(
                              color: _Brand.textMuted,
                              fontSize: 12,
                              fontFamily: 'RobotoMono'),
                        ),
                        const SizedBox(width: 6),
                        Text(
                          '${m['price'] ?? 0} UGX',
                          style: const TextStyle(
                            color: _Brand.amber,
                            fontSize: 12,
                            fontWeight: FontWeight.w700,
                            fontFamily: 'RobotoMono',
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ── 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 driverPhone = driver != null ? driver['phone'] as String? : null;
    final driverName =
        driver != null ? (driver['name'] ?? driver['phone'] ?? '—') : '—';

    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: [
            // Header
            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),
            const Divider(color: _Brand.divider, height: 1),
            const SizedBox(height: 16),

            // Driver info
            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,
                            )),
                      ],
                    ),
                  ),
                  if (driverPhone != null)
                    GestureDetector(
                      onTap: () async {
                        final uri = Uri(scheme: 'tel', path: driverPhone);
                        if (await canLaunchUrl(uri)) await launchUrl(uri);
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 14, vertical: 8),
                        decoration: BoxDecoration(
                          color: _Brand.amberGlow,
                          borderRadius: BorderRadius.circular(8),
                          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,
                                )),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            ] else
              const Text('Awaiting driver assignment…',
                  style:
                      TextStyle(color: _Brand.textMuted, fontSize: 13)),
          ],
        ),
      ),
    );
  }
}

// ── Action grid ───────────────────────────────────────────────────────────────

class _ActionGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final actions = [
      _ActionItem(
        label: 'Gas',
        subtitle: 'Cylinder delivery',
        icon: Icons.propane_tank_rounded,
        accent: const Color(0xFFFF9500),
        onTap: () {},
      ),
      _ActionItem(
        label: 'Fuel',
        subtitle: 'Petrol & Diesel',
        icon: Icons.local_gas_station_rounded,
        accent: const Color(0xFF0A84FF),
        onTap: () {},
      ),
      _ActionItem(
        label: 'Rescue+',
        subtitle: 'Emergency refill',
        icon: Icons.emergency_rounded,
        accent: const Color(0xFFFF4545),
        onTap: () {},
      ),
      _ActionItem(
        label: 'Shop',
        subtitle: 'Accessories',
        icon: Icons.shopping_bag_rounded,
        accent: const Color(0xFF34C759),
        onTap: () {},
      ),
    ];

    return GridView.count(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: 2,
      mainAxisSpacing: 12,
      crossAxisSpacing: 12,
      childAspectRatio: 1.05,
      children: actions.map((a) => _ActionCard(item: a)).toList(),
    );
  }
}

class _ActionItem {
  final String label, subtitle;
  final IconData icon;
  final Color accent;
  final VoidCallback onTap;
  const _ActionItem(
      {required this.label,
      required this.subtitle,
      required this.icon,
      required this.accent,
      required this.onTap});
}

class _ActionCard extends StatelessWidget {
  final _ActionItem item;
  const _ActionCard({required this.item});

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _Brand.card,
      borderRadius: BorderRadius.circular(16),
      child: InkWell(
        onTap: item.onTap,
        borderRadius: BorderRadius.circular(16),
        splashColor: item.accent.withOpacity(0.1),
        highlightColor: item.accent.withOpacity(0.05),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: _Brand.divider, width: 1),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // Icon badge
              Container(
                width: 42,
                height: 42,
                decoration: BoxDecoration(
                  color: item.accent.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(11),
                  border: Border.all(
                      color: item.accent.withOpacity(0.3), width: 1),
                ),
                child:
                    Icon(item.icon, color: item.accent, size: 22),
              ),
              // Label
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item.label,
                      style: const TextStyle(
                        color: _Brand.textPrimary,
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                      )),
                  const SizedBox(height: 2),
                  Text(item.subtitle,
                      style: const TextStyle(
                        color: _Brand.textMuted,
                        fontSize: 11,
                      )),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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