import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
// import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:lba/res/colors.dart';
import 'package:lba/widgets/app_snackbar.dart';

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

  @override
  State<MapSelectionScreen> createState() => _MapSelectionScreenState();
}

class _MapSelectionScreenState extends State<MapSelectionScreen> {
  final MapController _mapController = MapController();
  LatLng _currentCenter = const LatLng(25.1972, 55.2744);
  String _addressText = "Loading address...";
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _getAddressFromLatLng(_currentCenter);
  }

  Future<void> _getAddressFromLatLng(LatLng latLng) async {
    try {
      // List<Placemark> placemarks =`
      //     await placemarkFromCoordinates(latLng.latitude, latLng.longitude);
      // if (placemarks.isNotEmpty) {
      //   final p = placemarks.first;
      //   setState(() {
      //     _addressText =
      //         "${p.street ?? ''}, ${p.locality ?? ''}, ${p.country ?? ''}".trim().replaceAll(RegExp(r'^,|, $'), '');
      //   });
      // }
      setState(() {
        _addressText = "Lat: ${latLng.latitude.toStringAsFixed(4)}, Lng: ${latLng.longitude.toStringAsFixed(4)}";
      });
    } catch (e) {
      setState(() {
        _addressText = "Could not get address";
      });
      print(e);
    }
  }

  Future<void> _goToCurrentUserLocation() async {
    setState(() => _isLoading = true);

    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      AppSnackBar.showWarning(
        context: context,
        message: 'Location services are disabled. Please enable them in settings.',
        actionLabel: 'Settings',
        onActionPressed: () => Geolocator.openLocationSettings(),
      );
      setState(() => _isLoading = false);
      return;
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        AppSnackBar.showError(
          context: context,
          message: 'Location permissions are denied.',
        );
        setState(() => _isLoading = false);
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      AppSnackBar.showError(
        context: context,
        message: 'Location permissions are permanently denied, we cannot request permissions.',
        duration: const Duration(seconds: 5),
      );
      setState(() => _isLoading = false);
      return;
    }

    try {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high);
      final userLatLng = LatLng(position.latitude, position.longitude);
      _mapController.move(userLatLng, 15.0);
      await _getAddressFromLatLng(userLatLng);
    } catch (e) {
      print("Error getting current location: $e");
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Select Delivery Address', 
          style: TextStyle(color: AppColors.textPrimary, fontSize: 18)),
        backgroundColor: AppColors.surface,
        iconTheme: IconThemeData(color: AppColors.textPrimary),
        elevation: 1,
      ),
      body: Stack(
        children: [
          FlutterMap(
            mapController: _mapController,
            options: MapOptions(
              initialCenter: _currentCenter,
              initialZoom: 14.0,
              onPositionChanged: (position, hasGesture) {
                if (hasGesture) {
                   _currentCenter = position.center;
                  _getAddressFromLatLng(_currentCenter);
                }
              },
            ),
            children: [
              TileLayer(
                urlTemplate: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png',
                userAgentPackageName: 'com.example.lba',
                subdomains: const ['a', 'b', 'c', 'd'],
                additionalOptions: const {
                  'attribution': '© CARTO © OpenStreetMap contributors',
                },
              ),
            ],
          ),
          Center(
            child: Icon(
              Icons.location_pin,
              color: AppColors.offerTimer,
              size: 50,
            ),
          ),
          Positioned(
            top: 16,
            right: 16,
            child: FloatingActionButton(
              onPressed: _goToCurrentUserLocation,
              backgroundColor: AppColors.surface,
              child: _isLoading
                  ? CircularProgressIndicator(color: AppColors.primary)
                  : Icon(Icons.my_location, color: AppColors.primary),
            ),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: AppColors.surface,
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                boxShadow: [
                  BoxShadow(
                    color: AppColors.shadowColor,
                    blurRadius: 10,
                    offset: Offset(0, -2),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Selected Address:',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    _addressText,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: AppColors.textSecondary),
                  ),
                  const SizedBox(height: 16),
                  SizedBox(
                    width: double.infinity,
                    height: 50,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context, _addressText);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.offerTimer,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text(
                        'Confirm Address',
                        style: TextStyle(
                          color: AppColors.surface,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}