import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';

import 'package:doormile/main.dart';
import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/utils/snackbar_utils.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';
import 'package:doormile/features/booking/screens/booking_scaffold.dart';

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

  @override
  State<BookingPickupScreen> createState() => _BookingPickupScreenState();
}

class _BookingPickupScreenState extends State<BookingPickupScreen> {
  late final TextEditingController _pickup;
  late final TextEditingController _destPincode;
  late final TextEditingController _name;
  late final TextEditingController _mobile;
  late final TextEditingController _notes;
  late final _formKey = GlobalKey<FormState>();
  bool _loading = false;
  
  String _category = '';
  String _serviceType = '';

  @override
  void initState() {
    super.initState();
    final draft = context.read<AppState>().draft;
    _pickup = TextEditingController(text: draft.pickupAddress);
    _destPincode = TextEditingController(text: draft.dropPincode);
    _name = TextEditingController(text: draft.contactName);
    _mobile = TextEditingController(text: draft.contactMobile);
    _notes = TextEditingController(text: draft.notes);
    _category = draft.parcelType;
    _serviceType = draft.service;
  }

  @override
  void dispose() {
    _pickup.dispose();
    _destPincode.dispose();
    _name.dispose();
    _mobile.dispose();
    _notes.dispose();
    super.dispose();
  }

  void _showValidationError(String title, String message) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (ctx) => Container(
        padding: const EdgeInsets.all(24),
        decoration: const BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.error_outline_rounded, size: 56, color: AppColors.error),
              const SizedBox(height: 16),
              Text(title, style: AppTheme.headlineSm),
              const SizedBox(height: 8),
              Text(
                message,
                textAlign: TextAlign.center,
                style: AppTheme.bodyLg.copyWith(color: AppColors.onSurfaceVariant),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: FilledButton(
                  onPressed: () => Navigator.pop(ctx),
                  style: FilledButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                  ),
                  child: const Text('Got it'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _submit() async {
    if (_pickup.text.trim().isEmpty) {
      _showValidationError('Missing Location', 'Please enter or select a pickup address where the Miler should arrive.');
      return;
    }
    if (_destPincode.text.trim().length < 6) {
      _showValidationError('Missing Pincode', 'Please enter the 6-digit receiver pincode so we can estimate the fare.');
      return;
    }
    if (_category.isEmpty) {
      _showValidationError('Missing Category', 'Please select a parcel category so we can assign the right Miler.');
      return;
    }
    if (_serviceType.isEmpty) {
      _showValidationError('Missing Service Type', 'Please select whether you need Normal or Express delivery.');
      return;
    }
    
    final appState = context.read<AppState>();
    final draft = appState.draft;
    draft.pickupAddress = _pickup.text;
    draft.dropPincode = _destPincode.text.trim();
    draft.contactName = _name.text;
    draft.contactMobile = _mobile.text;
    draft.notes = _notes.text;
    draft.parcelType = _category;
    draft.service = _serviceType;

    // Extract pincode from typed address if GPS/saved address didn't set it.
    if (draft.pickupPincode.isEmpty) {
      final match = RegExp(r'\b\d{6}\b').firstMatch(_pickup.text);
      if (match != null) draft.pickupPincode = match.group(0)!;
    }

    if (draft.pickupPincode.isEmpty) {
      _showValidationError('Missing Pickup Pincode',
          'We couldn\'t detect a pincode for your pickup address. Please use "Use GPS current location", pick a saved address, or include the 6-digit pincode in the address.');
      return;
    }

    setState(() => _loading = true);
    await appState.fetchPriceEstimate();
    setState(() => _loading = false);
    
    if (mounted) Navigator.pushNamed(context, Routes.bookingPreview);
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AppState>();
    return BookingScaffold(
      title: 'Book a Pickup',
      step: 1,
      stepLabel: 'Pickup Request',
      buttonLabel: 'Review Booking',
      enabled: !_loading,
      loading: _loading,
      onContinue: _submit,
      children: [
        // Pickup location card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 24,
                    height: 24,
                    decoration: BoxDecoration(
                      color: AppColors.success.withValues(alpha: 0.15),
                      borderRadius: BorderRadius.circular(999),
                    ),
                    child: const Icon(Icons.location_on, size: 14, color: AppColors.success),
                  ),
                  const SizedBox(width: 10),
                  Text('PICKUP LOCATION',
                      style: AppTheme.caption.copyWith(
                          letterSpacing: 1, fontWeight: FontWeight.w600)),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                controller: _pickup,
                style: AppTheme.headlineSm,
                cursorColor: AppColors.primary,
                maxLines: 2,
                minLines: 1,
                decoration: const InputDecoration(
                  isDense: true,
                  border: InputBorder.none,
                  hintText: 'Enter pickup address manually',
                ),
              ),
              const Divider(height: 20, color: AppColors.surfaceContainer),
              InkWell(
                onTap: () async {
                  setState(() => _loading = true);
                  
                  try {
                    LocationPermission permission = await Geolocator.checkPermission();
                    if (permission == LocationPermission.denied) {
                      permission = await Geolocator.requestPermission();
                      if (permission == LocationPermission.denied) {
                        throw Exception('Location permissions are denied');
                      }
                    }
                    
                    if (permission == LocationPermission.deniedForever) {
                      if (!mounted) return;
                      setState(() => _loading = false);
                      bool? open = await showDialog<bool>(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: const Text('Permission Denied'),
                          content: const Text('Location permissions are permanently denied. Please enable them in app settings.'),
                          actions: [
                            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
                            TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Settings')),
                          ],
                        ),
                      );
                      if (open == true) await Geolocator.openAppSettings();
                      return;
                    }

                    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
                    if (!serviceEnabled) {
                      if (!mounted) return;
                      setState(() => _loading = false);
                      _showLocationDisabledSheet();
                      return;
                    } 

                    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
                    List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
                    
                    if (!mounted) return;
                    setState(() => _loading = false);
                    
                    final state = context.read<AppState>();
                    if (placemarks.isNotEmpty) {
                      final place = placemarks.first;
                      final area = '${place.subLocality ?? place.locality}, ${place.administrativeArea}';
                      final pincode = place.postalCode ?? '';
                      final fullAddress = '${place.street}, $area, $pincode';
                      _showLocationConfirmationSheet(context, state, area, pincode, fullAddress, position.latitude, position.longitude);
                    } else {
                      throw Exception('Could not determine address from coordinates.');
                    }
                  } catch (e) {
                    if (!mounted) return;
                    setState(() => _loading = false);
                    SnackbarUtils.showError(context, e.toString());
                  }
                },
                child: Row(
                  children: [
                    if (_loading) 
                      const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary))
                    else
                      const Icon(Icons.my_location, size: 18, color: AppColors.primary),
                    const SizedBox(width: 8),
                    Flexible(
                      child: Text(_loading ? 'Locating...' : 'Use GPS current location',
                          style: AppTheme.labelMd.copyWith(color: AppColors.primary),
                          overflow: TextOverflow.ellipsis),
                    ),
                  ],
                ),
              ),
              const Divider(height: 20, color: AppColors.surfaceContainer),
              Text('SAVED ADDRESSES', style: AppTheme.caption.copyWith(letterSpacing: 1, fontWeight: FontWeight.w600)),
              const SizedBox(height: 12),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                clipBehavior: Clip.none,
                child: Row(
                  children: [
                    _SavedAddressChip(
                      icon: Icons.home_rounded,
                      label: 'Home',
                      address: '12th Main, Indiranagar, Bengaluru, Karnataka 560038',
                      pincode: '560038',
                      onSelect: (addr, pin) => setState(() {
                        _pickup.text = addr;
                        final state = context.read<AppState>();
                        state.draft.pickupPincode = pin;
                        _name.text = state.firstName;
                        _mobile.text = state.phone;
                      }),
                    ),
                    const SizedBox(width: 12),
                    _SavedAddressChip(
                      icon: Icons.business_rounded,
                      label: 'Office',
                      address: 'Sector 4, HSR Layout, Bengaluru, Karnataka 560102',
                      pincode: '560102',
                      onSelect: (addr, pin) => setState(() {
                        _pickup.text = addr;
                        final state = context.read<AppState>();
                        state.draft.pickupPincode = pin;
                        _name.text = state.firstName;
                        _mobile.text = state.phone;
                      }),
                    ),
                    const SizedBox(width: 12),
                    _SavedAddressChip(
                      icon: Icons.favorite_rounded,
                      label: "Mom's House",
                      address: 'Jayanagar 4th Block, Bengaluru, Karnataka 560011',
                      pincode: '560011',
                      onSelect: (addr, pin) => setState(() {
                        _pickup.text = addr;
                        final state = context.read<AppState>();
                        state.draft.pickupPincode = pin;
                        _name.text = state.firstName;
                        _mobile.text = state.phone;
                      }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        
        // Destination Pincode card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 24,
                    height: 24,
                    decoration: BoxDecoration(
                      color: AppColors.primary.withValues(alpha: 0.15),
                      borderRadius: BorderRadius.circular(999),
                    ),
                    child: const Icon(Icons.pin_drop, size: 14, color: AppColors.primary),
                  ),
                  const SizedBox(width: 10),
                  Text('RECEIVER PINCODE',
                      style: AppTheme.caption.copyWith(
                          letterSpacing: 1, fontWeight: FontWeight.w600)),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                controller: _destPincode,
                keyboardType: TextInputType.number,
                maxLength: 6,
                style: AppTheme.headlineSm,
                cursorColor: AppColors.primary,
                decoration: const InputDecoration(
                  isDense: true,
                  border: InputBorder.none,
                  counterText: "",
                  hintText: 'Enter 6-digit delivery pincode',
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        
        // Category Card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Category',
                  style: AppTheme.caption.copyWith(
                      letterSpacing: 1, fontWeight: FontWeight.w600)),
              const SizedBox(height: 12),
              Column(
                children: [
                  Row(
                    children: [
                      Expanded(child: _SelectionCard(width: null, icon: Icons.category, label: 'General Goods', selected: _category == 'General Goods', onTap: () => setState(() => _category = 'General Goods'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.menu_book, label: 'Books & Documents', selected: _category == 'Books & Documents', onTap: () => setState(() => _category = 'Books & Documents'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.devices, label: 'Electronics & Gadgets', selected: _category == 'Electronics & Gadgets', onTap: () => setState(() => _category = 'Electronics & Gadgets'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.checkroom, label: 'Clothing & Textiles', selected: _category == 'Clothing & Textiles', onTap: () => setState(() => _category = 'Clothing & Textiles'))),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Row(
                    children: [
                      Expanded(child: _SelectionCard(width: null, icon: Icons.wine_bar, label: 'Fragile Items', selected: _category == 'Fragile Items', onTap: () => setState(() => _category = 'Fragile Items'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.medical_services, label: 'Medical & Pharma', selected: _category == 'Medical & Pharma', onTap: () => setState(() => _category = 'Medical & Pharma'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.directions_car, label: 'Automotive Parts', selected: _category == 'Automotive Parts', onTap: () => setState(() => _category = 'Automotive Parts'))),
                      const SizedBox(width: 8),
                      Expanded(child: _SelectionCard(width: null, icon: Icons.restaurant, label: 'Food & Perishables', selected: _category == 'Food & Perishables', onTap: () => setState(() => _category = 'Food & Perishables'))),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        



        
        // Type Card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Service Type',
                  style: AppTheme.caption.copyWith(
                      letterSpacing: 1, fontWeight: FontWeight.w600)),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    child: _ServiceCard(
                      title: 'Normal',
                      subtitle: 'Standard delivery',
                      icon: Icons.local_shipping_outlined,
                      selected: _serviceType == 'Normal',
                      onTap: () => setState(() => _serviceType = 'Normal'),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: _ServiceCard(
                      title: 'Express',
                      subtitle: 'Lightning fast',
                      icon: Icons.bolt,
                      selected: _serviceType == 'Express',
                      onTap: () => setState(() => _serviceType = 'Express'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),

        // Contact Details Card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Contact Person (Optional)',
                  style: AppTheme.caption.copyWith(
                      letterSpacing: 1, fontWeight: FontWeight.w600)),
              const SizedBox(height: 12),
              TextField(
                controller: _name,
                style: AppTheme.bodyLg,
                decoration: InputDecoration(
                  hintText: 'Name (e.g. Arun)',
                  isDense: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.outlineVariant),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.primary),
                  ),
                ),
              ),
              const SizedBox(height: 12),
              TextField(
                controller: _mobile,
                keyboardType: TextInputType.phone,
                style: AppTheme.bodyLg,
                decoration: InputDecoration(
                  hintText: 'Mobile Number',
                  isDense: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.outlineVariant),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.primary),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        
        // Notes Card
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Pickup Notes (Optional)',
                  style: AppTheme.caption.copyWith(
                      letterSpacing: 1, fontWeight: FontWeight.w600)),
              const SizedBox(height: 12),
              TextField(
                controller: _notes,
                maxLines: 3,
                style: AppTheme.bodyLg,
                decoration: InputDecoration(
                  hintText: 'Call before coming, Shop closes at 8 PM, etc.',
                  isDense: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.outlineVariant),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: const BorderSide(color: AppColors.primary),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        
        Text('RECENT & SAVED',
            style: AppTheme.caption
                .copyWith(letterSpacing: 1.2, fontWeight: FontWeight.w700)),
        const SizedBox(height: 12),
        ...state.savedAddresses.map((a) => Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: AppCard(
                onTap: () {
                  final draft = context.read<AppState>().draft;
                  draft.pickupPincode = a.pincode;
                  draft.pickupLatitude = a.latitude;
                  draft.pickupLongitude = a.longitude;
                  setState(() => _pickup.text = '${a.label}, ${a.line}');
                },
                child: Row(
                  children: [
                    IconBadge(
                        icon: a.icon, bg: a.iconBg, color: a.iconColor, circle: true),
                    const SizedBox(width: 14),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(a.label, style: AppTheme.labelMd),
                          const SizedBox(height: 2),
                          Text(a.line, style: AppTheme.caption),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )),
        const SizedBox(height: 8),
        const EcoBanner(
            text: 'Miler will collect parcel details, weight, and pricing upon arrival.'),
      ],
    );
  }

  void _showLocationConfirmationSheet(BuildContext context, AppState state, String area, String pincode, String fullAddress, double latitude, double longitude) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        padding: const EdgeInsets.all(24),
        decoration: const BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                height: 120,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: AppColors.surfaceContainerHigh,
                  borderRadius: BorderRadius.circular(16),
                  image: const DecorationImage(
                    image: AssetImage('assets/images/map_placeholder.png'), // Will failover smoothly if missing
                    fit: BoxFit.cover,
                  ),
                ),
                child: const Center(
                  child: IconBadge(icon: Icons.location_on, bg: AppColors.primaryContainer, color: AppColors.primary, circle: true),
                ),
              ),
              const SizedBox(height: 24),
              Text('GPS Location Found', style: AppTheme.headlineSm),
              const SizedBox(height: 8),
              Text(area, style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
              const SizedBox(height: 4),
              Text('Pincode: $pincode', style: AppTheme.caption),
              const SizedBox(height: 24),
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Navigator.pop(context),
                      style: OutlinedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                      ),
                      child: const Text('Cancel'),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: PrimaryButton(
                      label: 'Confirm',
                      onPressed: () {
                        state.draft.pickupPincode = pincode;
                        state.draft.pickupLatitude = latitude;
                        state.draft.pickupLongitude = longitude;
                        setState(() {
                          _pickup.text = fullAddress;
                          _name.text = state.firstName;
                          _mobile.text = state.phone;
                        });
                        Navigator.pop(context);
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showLocationDisabledSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (ctx) => Container(
        padding: const EdgeInsets.all(24),
        decoration: const BoxDecoration(
          color: AppColors.surface,
          borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.location_off_rounded, size: 64, color: AppColors.error),
              const SizedBox(height: 16),
              Text(
                "Location is turned off",
                style: AppTheme.headlineSm,
              ),
              const SizedBox(height: 8),
              Text(
                "Please turn on location to accurately detect your pickup address.",
                textAlign: TextAlign.center,
                style: AppTheme.bodyLg.copyWith(color: AppColors.onSurfaceVariant),
              ),
              const SizedBox(height: 24),
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () => Navigator.pop(ctx),
                      style: OutlinedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                      ),
                      child: const Text('Cancel'),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: PrimaryButton(
                      label: 'Turn On',
                      onPressed: () async {
                        Navigator.pop(ctx);
                        await Geolocator.openLocationSettings();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _SavedAddressChip extends StatelessWidget {
  final IconData icon;
  final String label;
  final String address;
  final String pincode;
  final Function(String address, String pincode) onSelect;

  const _SavedAddressChip({
    required this.icon,
    required this.label,
    required this.address,
    required this.pincode,
    required this.onSelect,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => onSelect(address, pincode),
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
        decoration: BoxDecoration(
          border: Border.all(color: AppColors.surfaceContainerHigh),
          borderRadius: BorderRadius.circular(12),
          color: AppColors.surface,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 16, color: AppColors.primary),
            const SizedBox(width: 8),
            Text(label, style: AppTheme.labelMd),
          ],
        ),
      ),
    );
  }
}

class _SelectionCard extends StatelessWidget {
  final IconData icon;
  final String label;
  final bool selected;
  final VoidCallback onTap;
  final double? width;

  const _SelectionCard({
    required this.icon,
    required this.label,
    required this.selected,
    required this.onTap,
    this.width = 85,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        width: width,
        padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4),
        decoration: BoxDecoration(
          color: selected ? AppColors.primaryFixed : AppColors.surface,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: selected ? AppColors.primary : AppColors.surfaceContainerHigh,
            width: selected ? 2 : 1,
          ),
          boxShadow: selected
              ? [BoxShadow(color: AppColors.primary.withValues(alpha: 0.15), blurRadius: 12, offset: const Offset(0, 4))]
              : [],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, color: selected ? AppColors.primary : AppColors.onSurfaceVariant, size: 24),
            const SizedBox(height: 12),
            Text(
              label,
              textAlign: TextAlign.center,
              maxLines: 2,
              style: AppTheme.labelMd.copyWith(
                color: selected ? AppColors.primary : AppColors.onSurfaceVariant,
                fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
                fontSize: 10,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ServiceCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final IconData icon;
  final bool selected;
  final VoidCallback onTap;

  const _ServiceCard({
    required this.title,
    required this.subtitle,
    required this.icon,
    required this.selected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          gradient: selected
              ? const LinearGradient(
                  colors: [AppColors.primaryContainer, AppColors.primary],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                )
              : null,
          color: selected ? null : AppColors.surface,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: selected ? AppColors.primary : AppColors.surfaceContainerHigh,
            width: selected ? 2 : 1,
          ),
          boxShadow: selected
              ? [BoxShadow(color: AppColors.primary.withValues(alpha: 0.3), blurRadius: 16, offset: const Offset(0, 6))]
              : [],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: selected ? Colors.white.withValues(alpha: 0.2) : AppColors.surfaceContainer,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(icon, color: selected ? Colors.white : AppColors.onSurfaceVariant, size: 24),
            ),
            const SizedBox(height: 16),
            Text(
              title,
              style: AppTheme.headlineSm.copyWith(
                color: selected ? Colors.white : AppColors.onSurface,
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              subtitle,
              style: AppTheme.caption.copyWith(
                color: selected ? Colors.white.withValues(alpha: 0.8) : AppColors.onSurfaceVariant,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
