import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../api_client.dart';
import '../widgets/banner_ad_widget.dart';
import 'gas_flow_screen.dart';
import 'fuel_flow_screen.dart';
import 'rescue_flow_screen.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 blue = Color(0xFF0A84FF);
  static const red = Color(0xFFFF4545);
  static const error = Color(0xFFFF4545);
}

// ── Service metadata ──────────────────────────────────────────────────────────
class _ServiceMeta {
  final Color accent;
  final Color accentGlow;
  final IconData icon;
  final String subtitle;

  const _ServiceMeta({
    required this.accent,
    required this.accentGlow,
    required this.icon,
    required this.subtitle,
  });
}

_ServiceMeta _metaFor(String name) {
  final n = name.toLowerCase();
  if (n.contains('gas')) {
    return const _ServiceMeta(
      accent: _Brand.amber,
      accentGlow: Color(0x33FF9500),
      icon: Icons.propane_tank_rounded,
      subtitle: 'Gas delivery to your door',
    );
  } else if (n.contains('fuel')) {
    return const _ServiceMeta(
      accent: _Brand.blue,
      accentGlow: Color(0x220A84FF),
      icon: Icons.local_gas_station_rounded,
      subtitle: 'Fuel on demand',
    );
  } else if (n.contains('rescue')) {
    return const _ServiceMeta(
      accent: _Brand.red,
      accentGlow: Color(0x22FF4545),
      icon: Icons.emergency_rounded,
      subtitle: 'Emergency roadside help',
    );
  }
  return const _ServiceMeta(
    accent: _Brand.amber,
    accentGlow: Color(0x33FF9500),
    icon: Icons.bolt_rounded,
    subtitle: 'On-demand service',
  );
}

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

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

  final VoidCallback onUnauthorized;
  final VoidCallback? onOrderCreated;

  @override
  State<ServicesScreen> createState() => _ServicesScreenState();
}

class _ServicesScreenState extends State<ServicesScreen> {
  late Dio _dio;
  List<dynamic> _services = [];
  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/services');
      if (!mounted) return;
      setState(() {
        _services = (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 services';
        });
      }
    }
  }

  void _navigateToService(BuildContext context, String name) {
    if (name.toLowerCase().contains('gas')) {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => GasFlowScreen(
                  onUnauthorized: widget.onUnauthorized,
                  onOrderCreated: widget.onOrderCreated,
                )),
      );
    } else if (name.toLowerCase().contains('fuel')) {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => FuelFlowScreen(
                  onUnauthorized: widget.onUnauthorized,
                  onOrderCreated: widget.onOrderCreated,
                )),
      );
    } else if (name.toLowerCase().contains('rescue')) {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => RescueFlowScreen(
                  onUnauthorized: widget.onUnauthorized,
                  onOrderCreated: widget.onOrderCreated,
                )),
      );
    }
  }

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

    // Error state
    if (_error != null && _services.isEmpty) {
      return 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.wifi_off_rounded,
                  color: _Brand.error, size: 32),
            ),
            const SizedBox(height: 16),
            const Text('Failed to load services',
                style: TextStyle(color: _Brand.textPrimary, fontSize: 15)),
            const SizedBox(height: 6),
            const Text('Pull down to retry',
                style: TextStyle(color: _Brand.textMuted, fontSize: 13)),
          ],
        ),
      );
    }

    // Build sorted list with fallback
    List<dynamic> list = _services.isNotEmpty
        ? List<dynamic>.from(_services)
        : [
            {'name': 'Gas', 'image_url': null},
            {'name': 'Fuel', 'image_url': null},
            {'name': 'Rescue+', 'image_url': null},
          ];

    list.sort((a, b) {
      final na = (a is Map ? a['name'] : '').toString().toLowerCase();
      final nb = (b is Map ? b['name'] : '').toString().toLowerCase();
      if (na.contains('gas')) return -1;
      if (nb.contains('gas')) return 1;
      if (na.contains('fuel')) return -1;
      if (nb.contains('fuel')) return 1;
      return 0;
    });

    return RefreshIndicator(
      onRefresh: _load,
      color: _Brand.amber,
      backgroundColor: _Brand.card,
      child: ListView(
        padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
        children: [
          // Section header
          const Padding(
            padding: EdgeInsets.only(top: 12, bottom: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'OUR SERVICES',
                  style: TextStyle(
                    color: _Brand.textMuted,
                    fontSize: 10,
                    letterSpacing: 2.5,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  'What do you need?',
                  style: TextStyle(
                    color: _Brand.textPrimary,
                    fontSize: 22,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ],
            ),
          ),

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

          // Service cards
          ...list.asMap().entries.map((entry) {
            final i = entry.key;
            final s = entry.value as Map;
            final name = s['name']?.toString() ?? 'Service';
            final imageUrl = s['image_url']?.toString();
            return Padding(
              padding: const EdgeInsets.only(bottom: 14),
              child: _ServiceCard(
                title: name,
                imageUrl:
                    imageUrl != null && imageUrl.isNotEmpty ? imageUrl : null,
                meta: _metaFor(name),
                index: i,
                onTap: () => _navigateToService(context, name),
              ),
            );
          }),
        ],
      ),
    );
  }
}

// ── Service card ──────────────────────────────────────────────────────────────

class _ServiceCard extends StatelessWidget {
  const _ServiceCard({
    required this.title,
    required this.imageUrl,
    required this.meta,
    required this.index,
    required this.onTap,
  });

  final String title;
  final String? imageUrl;
  final _ServiceMeta meta;
  final int index;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(18),
        splashColor: meta.accent.withOpacity(0.08),
        highlightColor: meta.accent.withOpacity(0.04),
        child: Container(
          height: 130,
          decoration: BoxDecoration(
            color: _Brand.card,
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: _Brand.divider, width: 1),
            boxShadow: [
              BoxShadow(
                color: meta.accent.withOpacity(0.07),
                blurRadius: 20,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          clipBehavior: Clip.antiAlias,
          child: Row(
            children: [
              // Left: text content
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Icon badge
                      Container(
                        width: 36,
                        height: 36,
                        decoration: BoxDecoration(
                          color: meta.accentGlow,
                          borderRadius: BorderRadius.circular(9),
                          border: Border.all(
                              color: meta.accent.withOpacity(0.35), width: 1),
                        ),
                        child: Icon(meta.icon, color: meta.accent, size: 18),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        title,
                        style: const TextStyle(
                          color: _Brand.textPrimary,
                          fontSize: 17,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      const SizedBox(height: 3),
                      Text(
                        meta.subtitle,
                        style: const TextStyle(
                          color: _Brand.textMuted,
                          fontSize: 11,
                          height: 1.3,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // Right: image or illustrated placeholder (masked with round edges)
              SizedBox(
                width: 130,
                height: 130,
                child: ClipRRect(
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(18),
                    bottomRight: Radius.circular(18),
                  ),
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      if (imageUrl != null)
                        Image.network(
                          imageUrl!,
                          fit: BoxFit.cover,
                          errorBuilder: (_, __, ___) =>
                              _IllustrationPlaceholder(meta: meta),
                        )
                      else
                        _IllustrationPlaceholder(meta: meta),

                      // Left-to-right gradient fade
                      DecoratedBox(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              _Brand.card,
                              _Brand.card.withOpacity(0),
                            ],
                            stops: const [0.0, 0.45],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Illustration placeholder (when no image_url) ──────────────────────────────

class _IllustrationPlaceholder extends StatelessWidget {
  final _ServiceMeta meta;
  const _IllustrationPlaceholder({required this.meta});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: meta.accentGlow,
      child: Center(
        child: Opacity(
          opacity: 0.25,
          child: Icon(meta.icon, color: meta.accent, size: 64),
        ),
      ),
    );
  }
}