import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

// Uganda (Kampala) default center
const double _defaultLat = 0.3476;
const double _defaultLng = 32.5825;

// ── Design tokens (design.json) ───────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
  static const red = Color(0xFFFF4545);
  static const screenPadding = 20.0;
  static const inputRadius = 12.0;
  static const buttonRadius = 12.0;
}

/// Result returned when user saves: { 'lat': double, 'lng': double, 'name': String? }
class MapPickerScreen extends StatefulWidget {
  const MapPickerScreen({super.key});

  @override
  State<MapPickerScreen> createState() => _MapPickerScreenState();
}

class _MapPickerScreenState extends State<MapPickerScreen> {
  GoogleMapController? _mapController;
  LatLng _selected = const LatLng(_defaultLat, _defaultLng);
  final TextEditingController _nameController = TextEditingController();
  bool _loadingLocation = false;
  String? _error;
  bool _saving = false;

  static const CameraPosition _initialPosition = CameraPosition(
    target: LatLng(_defaultLat, _defaultLng),
    zoom: 14,
  );

  @override
  void initState() {
    super.initState();
    // Request location permission when screen opens so user can allow before using "Use my location"
    WidgetsBinding.instance.addPostFrameCallback((_) => _requestLocationPermissionOnce());
  }

  /// Request location permission once when map picker opens (so the system dialog appears and user can confirm).
  Future<void> _requestLocationPermissionOnce() async {
    if (!mounted) return;
    try {
      final serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) return; // Will show message when they tap "Use my location"
      LocationPermission permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        await Geolocator.requestPermission();
      }
    } catch (_) {
      // Ignore; permission will be requested again when they tap "Use my location"
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _mapController?.dispose();
    super.dispose();
  }

  Future<void> _useMyLocation() async {
    setState(() {
      _loadingLocation = true;
      _error = null;
    });
    try {
      bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) {
        setState(() {
          _error = 'Location services are disabled';
          _loadingLocation = false;
        });
        return;
      }
      LocationPermission permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
      }
      if (permission == LocationPermission.deniedForever) {
        setState(() {
          _error = 'Location permission permanently denied. Enable in settings.';
          _loadingLocation = false;
        });
        return;
      }
      if (permission == LocationPermission.denied) {
        setState(() {
          _error = 'Location permission denied';
          _loadingLocation = false;
        });
        return;
      }
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );
      final latLng = LatLng(position.latitude, position.longitude);
      setState(() {
        _selected = latLng;
        _loadingLocation = false;
        _error = null;
      });
      _mapController?.animateCamera(CameraUpdate.newLatLngZoom(latLng, 16));
    } catch (e) {
      setState(() {
        _error = 'Could not get location. Try again or tap on the map.';
        _loadingLocation = false;
      });
    }
  }

  void _onMapTap(LatLng position) {
    setState(() {
      _selected = position;
      _error = null;
    });
  }

  Future<void> _save() async {
    if (_saving) return;
    setState(() => _saving = true);
    await Future<void>.delayed(const Duration(milliseconds: 100));
    if (!mounted) return;
    final result = <String, dynamic>{
      'lat': _selected.latitude,
      'lng': _selected.longitude,
      'name': _nameController.text.trim().isEmpty ? null : _nameController.text.trim(),
    };
    Navigator.of(context).pop(result);
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: AppBar(
        backgroundColor: _Brand.surface,
        elevation: 0,
        scrolledUnderElevation: 0,
        title: const Text(
          'PIN LOCATION',
          style: TextStyle(
            fontFamily: 'RobotoMono',
            fontSize: 15,
            fontWeight: FontWeight.w700,
            letterSpacing: 3,
            color: _Brand.textPrimary,
          ),
        ),
        leading: Padding(
          padding: const EdgeInsets.only(left: 12),
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: _Brand.card,
                borderRadius: BorderRadius.circular(9),
                border: Border.all(color: _Brand.divider),
              ),
              child: const Icon(Icons.arrow_back_ios_new, size: 13, color: _Brand.textMuted),
            ),
          ),
        ),
        leadingWidth: 56,
      ),
      body: Stack(
        children: [
          GoogleMap(
            initialCameraPosition: _initialPosition,
            onMapCreated: (controller) => _mapController = controller,
            onTap: _onMapTap,
            markers: {
              Marker(
                markerId: const MarkerId('picked'),
                position: _selected,
                icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange),
              ),
            },
            myLocationEnabled: true,
            myLocationButtonEnabled: false,
            zoomControlsEnabled: false,
            mapToolbarEnabled: false,
            compassEnabled: false,
            liteModeEnabled: false,
          ),
          // Use my location button (bottom right, above the name/save card)
          Positioned(
            bottom: 220,
            right: _Brand.screenPadding,
            child: Material(
              color: _Brand.card,
              borderRadius: BorderRadius.circular(12),
              child: InkWell(
                onTap: _loadingLocation ? null : _useMyLocation,
                borderRadius: BorderRadius.circular(12),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: _Brand.divider),
                  ),
                  child: _loadingLocation
                      ? const SizedBox(
                          width: 24,
                          height: 24,
                          child: CircularProgressIndicator(
                            strokeWidth: 2.5,
                            valueColor: AlwaysStoppedAnimation(_Brand.amber),
                          ),
                        )
                      : const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.my_location_rounded, color: _Brand.amber, size: 20),
                            SizedBox(width: 8),
                            Text(
                              'Use my location',
                              style: TextStyle(
                                color: _Brand.amber,
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                ),
              ),
            ),
          ),
          // Hint
          Positioned(
            left: _Brand.screenPadding,
            right: _Brand.screenPadding,
            top: 16,
            child: IgnorePointer(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: _Brand.card.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(color: _Brand.divider),
                ),
                child: Text(
                  'Tap on the map to set your delivery point',
                  style: TextStyle(color: _Brand.textMuted, fontSize: 12),
                ),
              ),
            ),
          ),
          // Bottom card: name + save
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: EdgeInsets.fromLTRB(
                _Brand.screenPadding,
                20,
                _Brand.screenPadding,
                MediaQuery.of(context).padding.bottom + 20,
              ),
              decoration: BoxDecoration(
                color: _Brand.bg,
                border: Border(top: BorderSide(color: _Brand.divider)),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (_error != null) ...[
                    _ErrorBanner(_error!),
                    const SizedBox(height: 12),
                  ],
                  const Text(
                    'ADDRESS NAME',
                    style: TextStyle(
                      color: _Brand.textMuted,
                      fontSize: 10,
                      fontWeight: FontWeight.w600,
                      letterSpacing: 2.5,
                    ),
                  ),
                  const SizedBox(height: 8),
                  TextField(
                    controller: _nameController,
                    style: const TextStyle(
                      fontFamily: 'RobotoMono',
                      fontSize: 18,
                      letterSpacing: 2,
                      color: _Brand.textPrimary,
                    ),
                    decoration: InputDecoration(
                      hintText: 'e.g. Home, Office',
                      hintStyle: TextStyle(color: _Brand.textMuted, fontSize: 16, letterSpacing: 2),
                      filled: true,
                      fillColor: _Brand.card,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(_Brand.inputRadius),
                        borderSide: const BorderSide(color: _Brand.divider),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(_Brand.inputRadius),
                        borderSide: const BorderSide(color: _Brand.divider, width: 1.5),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(_Brand.inputRadius),
                        borderSide: const BorderSide(color: _Brand.amber, width: 1.5),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      counterText: '',
                    ),
                    cursorColor: _Brand.amber,
                  ),
                  const SizedBox(height: 16),
                  SizedBox(
                    height: 54,
                    child: FilledButton(
                      onPressed: _saving ? null : _save,
                      style: FilledButton.styleFrom(
                        backgroundColor: _Brand.amber,
                        foregroundColor: Colors.black,
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(_Brand.buttonRadius),
                        ),
                      ),
                      child: _saving
                          ? const SizedBox(
                              width: 24,
                              height: 24,
                              child: CircularProgressIndicator(
                                strokeWidth: 2.5,
                                color: Colors.black54,
                              ),
                            )
                          : const Text(
                              'SAVE ADDRESS',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w800,
                                letterSpacing: 2,
                              ),
                            ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

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

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